开发者

replacing object by a dummy before any imports and/or other statements get executed

I use USE_DUMMY which if it's set to True then a dummy is created for my module.

The question is: how do I set this variable (from an external module) BEFORE the import and/or other statements get executed?

a.py:

USE_DUMMY = False

def unvailable():
    print 'not available'

if USE_DUMMY is True:
    def dummy():
        print "this function is a dummy"
    unavailable = dummy

b.py:

import a
a.USE_DUMMY = True开发者_JS百科

Here it's already too late to set USE_DUMMY = True such that unavailable() gets binded by dummy() because the definitions were already executed.

If my question is not clear then I could elaborate it further ...


In contrast to some other languages, Python's import is simply an executable statement. This means that if you want to take some actions before importing some modules, you can simply place code before the relevant import.

In other words, if you need to set a global variable before any imports etc, you could place the assignment right at the top of your main script:

USE_DUMMIES=True
import abc, xyz
# do stuff

If that's not what you're asking, please clarify your question.


Found a solution by using builtin

For more info Python: How to make a cross-module variable?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜