Visibility of global variables in imported modules

前端 未结 8 1850
梦毁少年i
梦毁少年i 2020-11-22 11:22

I\'ve run into a bit of a wall importing modules in a Python script. I\'ll do my best to describe the error, why I run into it, and why I\'m tying this particular approach t

8条回答
  •  旧时难觅i
    2020-11-22 11:41

    As a workaround, you could consider setting environment variables in the outer layer, like this.

    main.py:

    import os
    os.environ['MYVAL'] = str(myintvariable)
    

    mymodule.py:

    import os
    
    myval = None
    if 'MYVAL' in os.environ:
        myval = os.environ['MYVAL']
    

    As an extra precaution, handle the case when MYVAL is not defined inside the module.

提交回复
热议问题