Home > Back-end >  How to Grab All Globals as a Reference in Python?
How to Grab All Globals as a Reference in Python?

Time:01-16

I'm working on a project that's written in Go and uses go-python to run Python code inside. The way it works is you write code.py snippits, then the Go code throws in Global variables to use the internal API.

i.e. code.py might look like:

some_api_call() # Linters think some_api_call is not defined, but go-python put it in the global scope

This works great, but for modularity I want my code.py to import code_2.py. Unfortunately, if I do this, code_2.py doesn't have acces to the API that the go code manually added to code.py's global scope.

i.e.

code.py:

import code2.py

code2.run_func()

code2.py:

def run_func():
  some_api_call() # This fails since code2.py doesn't have the API injected

I can pass in individual API functions to code_2.py manually, but there's a lot of them. It would be easier if I could just pass everything in code.py's Global scope, like code_2.init(Globals). Is there an easy way to do this? I've tried circular importing, but go-python doesn't let me import the originally called script.

Thanks!

CodePudding user response:

You can pass a paramter to code2.run_func(), and have run_func access api calls through its methods or classmethods.

Something like this. In code.py:

import code2.py

class Api:
    @classmethod
    def some_api_call(): ...

code2.run_func(Api)

And in code_2.py:

def run_func(api):
    api.some_api_call()

CodePudding user response:

Looks like the built-in method globals() will do the trick

code.py:

import code_2

code_2.init(globals())

code_2.py:

def init(other_global_scope):
    for k in other_global_scope:
        globals()[k] = other_global_scope[k]

# code_2.py can now run some_api_call()
  • Related