How to import standard library module instead of local directory?

前端 未结 3 1339
醉话见心
醉话见心 2021-02-20 14:43

I have a local directory named \"calendar\" with an \"__init__.py\" file.

I want \"import calendar\" to import the standard library module calendar, and not the module d

3条回答
  •  礼貌的吻别
    2021-02-20 15:25

    As the rest says, the best option is to rename the calendar module into a new module not used by standard library.

    But as a workaround if that's not possible, you could create a another module (visible in the syspath) outside the directory where the local calendar.py file is placed.

    So if you have a hierarchy like this:

    project/
       __init__.py
       app1/
          __init__.py
          calendar.py
          module_in_which_i_want_to_use_python_std_calendar.py
    

    You could create a new module named std_calendar.py outside apps (outside calendar.py is placed). In this file you could import calendar (this will be standard calendar module)

    from calendar import *
    

    And the hierarchy would be:

    project/
       __init__.py
       std_calendar.py
       app1/
          __init__.py
          calendar.py
          module_in_which_i_want_to_use_python_std_calendar.py
    

    In module_in_which_i_want_to_use_python_std_calendar.py you could use standard calendar with:

    from project import std_calendar as calendar
    

提交回复
热议问题