Search code examples
pythonglobal-variables

python find global variables of specific file without importing it


I'm making a module file, and I need to get the global variables of the file that is using it. I've tried importing it, and then getting the global variables of of that, but that gets me this error:

Traceback (most recent call last):
  File "C:\Users\isaac\OneDrive\Coding\python\logger\file.py", line 1, in <module>
    import logger
  File "C:\Users\isaac\OneDrive\Coding\python\logger\logger.py", line 3, in <module>
    import file as bla
  File "C:\Users\isaac\OneDrive\Coding\python\logger\file.py", line 3, in <module>
    log = logger.Logger('logfile', 'file')
AttributeError: partially initialized module 'logger' has no attribute 'Logger' (most likely due to a circular import)

Is there a way to get the global variables with open(...) or something like that?


Solution

  • There are two solutions to this. One is to take the global variables out of file and move them to a third file, say globals.py which can be imported by both.

    In terms of accessing global variables by opening the file, you can try and parse the file yourself, or indeed use something like AST. I imagine though that the aforementioned technique will be adequate for your use case.