module reimported if imported from different path

前端 未结 2 616
感动是毒
感动是毒 2021-01-02 11:31

In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may in

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 11:52

    I can only replicate this if main.py is the file you are actually running. In that case you will get the current directory of main.py on the sys path. But you apparently also have a system path set so that mypackage can be imported.

    Python will in that situation not realize that mymodule and mypackage.mymodule is the same module, and you get this effect. This change illustrates this:

    def add(x):
        from mypackage import mymodule
        print "mypackage.mymodule path", mymodule
        mymodule.l.append(x)
        print "updated list",mymodule.l
    
    def get():
        import mymodule
        print "mymodule path", mymodule
        return mymodule.l
    
    add(1)
    print "lets check",get()
    
    add(1)
    print "lets check again",get()
    
    
    $ export PYTHONPATH=.
    $ python  mypackage/main.py 
    
    mypackage.mymodule path 
    mymodule path 
    

    But add another mainfile, in the currect directory:

    realmain.py:
    from mypackage import main
    

    and the result is different:

    mypackage.mymodule path 
    mymodule path 
    

    So I suspect that you have your main python file within the package. And in that case the solution is to not do that. :-)

提交回复
热议问题