What could cause a python module to be imported twice?

后端 未结 1 1497
刺人心
刺人心 2020-11-27 19:55

As far as I understand, a python module is never imported twice, i.e. the code in the module only gets executed the first time it is imported. Subsequent import statements j

1条回答
  •  [愿得一人]
    2020-11-27 20:27

    A Python module can be imported twice if the module is found twice in the path. For example, say your project is laid out like so:

    • src/
      • package1/
        • spam.py
        • eggs.py

    Suppose your PYTHONPATH (sys.path) includes src and src/package1:

    PYTHONPATH=/path/to/src:/path/to/src/package1
    

    If that's the case, you can import the same module twice like this:

    from package1 import spam
    import spam
    

    And Python will think they are different modules. Is that what's going on?

    Also, per the discussion below (for users searching this question), another way a module can be imported twice is if there is an exception midway through the first import. For example, if spam imports eggs, but importing eggs results in an exception inside the module, it can be imported again.

    0 讨论(0)
提交回复
热议问题