0

Hello I am trying to import a class from another file and initialize it and use the global variables from the file where it is initialized but when I do globals() in the __init__ method in the class I get the global variables from the file where its made (the file that the class is defined in) not where its initialized does anyone know how I could do this?

Logtism
  • 125
  • 1
  • 6
  • 2
    If the variables are available in the file, why not pass them as arguments to the `__init__` method? – Iain Shelvington Jan 08 '22 at 02:25
  • 1
    Does this answer your question? [Visibility of global variables in imported modules](https://stackoverflow.com/questions/15959534/visibility-of-global-variables-in-imported-modules) – bb1 Jan 08 '22 at 02:31

1 Answers1

1

have you tried using the inspect module? Using inspect.stack() you can get info about different callers. I have used it to access the locals of the file that called the function containing the code, which let me hack together a really neat switch statement style context manager, so i would imagine you should be able to access the globals just as easily. See this link for more info on inspect and the interpreter stack.

Edit: I found that at the top of the inspect page on the first table it talks about frame objects and they have an attribute " f_globals global namespace seen by this frame" which is exactly what i was originally talking about. You would just need to initialise the object, have the object call a separate function, and in that function you would get the stack and the the last frame to access its globals

ZXYNINE
  • 712
  • 4
  • 5