Search code examples
pythonmoduleparameter-passingprogram-entry-pointpython-module

How to import a file as a module while passing parameters into the main code


I'm struggling with this small problem, I'm sure it has a simple solution but cannot find it.

I have one file called test1.py, and another called test2.py

My code for test1.py:

import test2(*Variable name*)
print(test2.add(1, 2))

My code for test2.py:

c = *Variable name*

def add(a, b):
    sum = a + b + c
    return sum

I want to be able to pass in a parameter, when importing test2.py into test1.py, which will be put into the main section of the code within test2.py

This is a simplified version of my problem and the variable c needs to be declared in the main code.

Thanks for any help!


Solution

  • I would go for a class:

    # test2.py
    class Test:
        def __init__(self, c):
            self.c = c
    
        def add(self, a, b):
            sum = a + b + self.c
            return sum
    

    In your test1 you simply import the Module, Instantiate a class, passing c into the constructor:

    from test2 import Test 
    t = Test(5)
    print(t.add(1,2)) # = 8