realtebo
realtebo

Reputation: 25691

Access 'main' module functions and vars from imported module

main.py

import try_modules
cats = 2
try_modules.printCats()

try_modules.py

def printCats():
    global cats
    print cats

This throw an error. What's the right way to use 'pseudo-global' vars from main module into imported modules?

Upvotes: 0

Views: 53

Answers (2)

vinit_ivar
vinit_ivar

Reputation: 650

Your main.py doesn't know what module the variable cats belongs to. Use

try_modules.cats = 2

or fix your import to read

from try_modules import cats

Upvotes: 0

lc2817
lc2817

Reputation: 3742

If you have that requirement, this is generally a bad design, but you can do:

 import try_modules
 try_modules.cats = 2
 try_modules.printCats()

If you have several module needing one variable put it in a module holding the variable (again I don't think this should be used, you should rather pass an object around holding the variable):

module_a.py

import global_vars

global_vars.a = 23

module_b.py

import global_vars

print global_vars.a

global_vars.py

a = 37

and main.py

import module_a
import module_b

will print 23, and the variable a is shared across all the modules.

Upvotes: 1

Related Questions