Calling a function in a separate file with parameters defined on the initial one

Viewed 132

Suppose I have the following in a python file with the name: file1.py

a=1
def f(x):
  return x+a

Now, in another file (Let's say file2.py) if I import the above function, that is: from file1 import f

and then, evaluate it at a certain value, say; print(f(2)) gives the value 3 because, 2+a=2+1=3. That means the code has used the value of a defined in file1.py

Also even if I have the file2 as,

from file1 import f
a=10
print(f(2))

It still gives the same answer as before. Which means the function has used the value of a defined in file1

So my question is, whether there is a way to write the code in file2 so that it uses the a defined there.
I know that I can define the function as

def f(x,a):
  return x+a

But for my case it would be really helpful, if I can leave the function only with one variable....

Appreciate your help

2 Answers

Much simpler solution, and without circular dependencies:

file1.py

a = 1
def f(x):
    return a + x

main.py

import file1
print(file1.f(10)) # will print 11
file1.a = 10
print(file1.f(10)) # will print 20

It is possible to use import statements within functions. So, if you wanted to, you could use this in file1.py:

a=1
def f(x):
  from file2 import a
  return x+a

In this case, the imported a would override the previously defined a, causing its value to be set to 10. To avoid this, you could use something like this:

a=1
def f(x):
  from file2 import a as b
  return x+b

While this method does work, be warned that using circular dependencies (two modules depending on each other) is generally considered bad practice. However, this is the only way I know of to achieve your intended design.

Related