0

I have files that define global variables which I would like to use outside of the files, e.g. "func.py" containing:

def init():
  global a
  a = 5

If I import via "from x import *", then accessing the module's global variables like this does not work:

from func import *
init()
a
func.a

as neither a nor func are defined. "func" is listed in sys.modules.keys(), however.

I know "from x import *" is not exactly best practice, but how can I access the module's variables or the module object when using it?

FvD
  • 1,286
  • 13
  • 25
  • Is func.py a full python script? In your case, you need to declare 'a' outside of 'init' and reference 'a' in 'init' with 'global' keyword. 'global' in a function would tell python to look for that variable 'outside' of that function. When use 'from ... import ...', it's expected that 'func' is undefined. If you need it, use 'import ...' – mission.liao Aug 04 '15 at 03:17
  • In this example it's just a collection of functions, but I guess it applies generally. – FvD Aug 04 '15 at 03:39

1 Answers1

0

I haven't found a way to do this other than importing the module "properly" as well.

import func
from func import *
init()
func.a

This question is very closely related. This one implies that since modules are imported fully with either command, there is no real performance difference either. This suggestion to use a separate file/container with global variables for larger projects is worth mentioning, too.

And obviously, don't use "from x import *" outside of live troubleshooting if you can't help it.

Community
  • 1
  • 1
FvD
  • 1,286
  • 13
  • 25