1

I have two files module.py and main.py

In module.py I have a function which uses a constant defined outside of its scope.

#module.py
def add(x):
    s = x + const
    return s
if __name__ == '__main__':
    const = 2
    print(add(2)) 

It prints 4 as output when run directly.

In main.py I have:

#main.py
import module as m

const = 2
print(m.add(2))

It gives error: NameError: name 'const' is not defined

Is there a way to make m.add() look for const in main.py global scope? I'd like not to pass const to add() as a function variable.

Myk Willis
  • 12,306
  • 4
  • 45
  • 62
Ricevind
  • 341
  • 1
  • 4
  • 15
  • 2
    Short answer: No, it’s not possible. You either have to make `const` a module member (e.g. `m.const = 2`), or pass it to the function. – poke Jan 28 '16 at 15:20
  • 2
    What's your real use case? Why wouldn't you want to pass a value to a function? That is how functions are supposed to work. – Daniel Roseman Jan 28 '16 at 15:23
  • I want to separate my model functions from simulation case. Some of those functions use same constants which i want to declare only once. Yet I'd like to have possibility to change them in simulation file. `m.const` does what i want – Ricevind Jan 28 '16 at 15:42
  • See here: https://stackoverflow.com/questions/4706879/global-variable-with-imports/38899557?noredirect=1#comment78306834_38899557 – Andrew Aug 14 '17 at 12:40

1 Answers1

0

It's not clear what your real use case is, but if you want to have a shared variable between modules you need to have that variable defined at module scope.

Declare it in one module:

#module.py
const = 0  # declare as global of module.py
def add(x):
    s = x + const
    return s
if __name__ == '__main__':
    const = 3
    print(add(2))

...and reference it in another:

#main.py
import module as m

m.const = 3  # reference module's variable 
print(m.add(2))
Myk Willis
  • 12,306
  • 4
  • 45
  • 62