Override globals in function imported from another module

前端 未结 3 1354
孤独总比滥情好
孤独总比滥情好 2020-12-21 19:25

Let\'s say I have two modules:

a.py

value = 3
def x()
    return value

b.py

from          


        
3条回答
  •  自闭症患者
    2020-12-21 19:50

    So I found a way to (sort of) do this, although I don't think it entirely solves your problems. Using inspect, you can access the global variables of the file calling your function. So if you set up your files like so:

    a.py

    import inspect
    
    value = 3
    
    def a():
        return inspect.stack()[1][0].f_globals['value']
    

    b.py

    from a import a
    
    value = 5
    
    print(a())
    

    The output is 5, instead of 3. However, if you imported both of these into a third file, it would look for the globals of the third file. Just wanted to share this snippet however.

提交回复
热议问题