Python modules with identical names (i.e., reusing standard module names in packages)

后端 未结 4 1111
死守一世寂寞
死守一世寂寞 2020-12-03 07:38

Suppose I have a package that contains modules:

SWS/
  __init.py__
  foo.py
  bar.py
  time.py

and the modules need to refer to functions c

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 08:25

    Reusing names of standard functions/classes/modules/packages is never a good idea. Try to avoid it as much as possible. However there are clean workarounds to your situation.

    The behaviour you see, importing your SWS.time instead of the stdlib time, is due to the semantics of import in ancient python versions (2.x). To fix it add:

    from __future__ import absolute_import
    

    at the very top of the file. This will change the semantics of import to that of python3.x, which are much more sensible. In that case the statement:

    import time
    

    Will only refer to a top-level module. So the interpreter will not consider your SWS.time module when executing that import inside the package, but it will only use the standard library one.

    If a module inside your package needs to import SWS.time you have the choice of:

    • Using an explicit relative import:

      from . import time
      
    • Using an absolute import:

      import SWS.time as time
      

    So, your foo.py would be something like:

    from __future__ import absolute_import
    
    import time
    
    from . import time as SWS_time
    

提交回复
热议问题