Python imports across modules and global variables

后端 未结 4 674
遇见更好的自我
遇见更好的自我 2020-12-19 10:00

I have a question which seems to be rather fundamental but I can\'t seem to find any help on this anywhere.

file_a.py >>

from xyz import XYZ
class A:
         


        
4条回答
  •  無奈伤痛
    2020-12-19 10:54

    Is my understanding wrong?

    Yes, because the line from file_a import A import only class A into the namespace of file_b. The namespace of file_a is left alone. If it were not like this, there would be little sense in having both syntax:

    import modulename
    from modulename import something
    

    as if your thinking was right, then after the second form you would always be able to use modulename.someotherthing.

    If yes, then is there a way to have common imports and global variables across files?

    Yes, with the star * operator:

    from modulename import *
    

    but this brings the issue of namespace pollution, for example from file_a import * will import in file_b also all the imports done in file_a. You will eventually lose control of your imports and this will bite you at some time... trust me on this!

    When for some reason from module import * is needed, a workaround to namespace pollution is to define in module the variable __all__, which whitelists what should be imported with the star operator.

    HTH!

提交回复
热议问题