Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I call globals() from an imported module?

let's say I have a module, spam. In spam, I put this code:

import __main__ 
print(__main__.globals())

Then, from any old python script, I import spam. From this I would get the following error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import spam
  File "/home/runner/spam.py", line 7, in <module>
    print(__main__.globals())
AttributeError: module '__main__' has no attribute 'globals'

But, however, when I do this inside of the script importing spam;

import spam
a = globals()

and I repeat the same code with one difference;

 ... 
print(eval(main_mod[0]).a)

I get the result I hoped for, which was a list of all the globals in __main__. Why can't I just call it normally? I don't want to have to code in a variable to hold globals() every time I import "spam". I'm sure others could benefit from this, I tried it with other builtins from __main__ like abs but same error. By the way, I'm trying to get __main__'s globals so that I can get the names of functions of whatever is importing spam. I need it so that I can also access variables from __main__.

like image 214
Corpus Shmorpus Avatar asked Jan 27 '26 12:01

Corpus Shmorpus


1 Answers

The global variables in a module are the contents of the module object's __dict__, not an attribute named globals. You can access the __dict__ of any object using the builtin function vars:

vars(eval(main_mod[0]))

I'd also suggest you use importlib rather than exec and eval with import statements:

import importlib

main = importlib.import_module('__main__')
main_by_name = importlib.import_module(main.__file__.split('.')[0])
main_globals = vars(main_by_name)
like image 164
Blckknght Avatar answered Jan 29 '26 01:01

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!