Injecting variables into an import namespace

前端 未结 2 724
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 11:37

To illustrate what I am trying to do, let\'s say I have a module testmod that lives in ./testmod.py. The entire contents of this module is

2条回答
  •  北海茫月
    2020-12-11 11:57

    You could screw with Python's builtins to inject your own fake built-in test variable:

    import builtins    # __builtin__, no s, in Python 2
    
    builtins.test = 5  # or whatever other placeholder value
    
    import testmod
    
    del builtins.test  # clean up after ourselves
    

提交回复
热议问题