1

I am using Python 3.10.

  1. I created a module os.py in a directory, my_dir.
  2. I am trying to access my os.py using import os, from my_dir directory.
  3. But it is loading Python's os module, not mine.
  4. I inserted my_dir in sys.path as a first element, but still it's loading Python's os module.
  5. I repeated the same with another standard library of Python 3, datetime. But it's working as expected. i.e., it's loading my datetime.py, not Python's.

Why does only the os module have this problem? Is it a bug in Python 3?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Arun
  • 59
  • 5

1 Answers1

1

if you want to import some module A that happens to have the name of some other module B, that its placement in the import hierarchy mean that module B is found first, then you need to use a relative import to clearly differentiate between the two from withing modules in the same package

for example, said you have

my_dir
    __init__.py
    os.py
    app.py

for app.py to use your os.py you do

from .os import X
Copperfield
  • 8,131
  • 3
  • 23
  • 29
  • Thanks! your reply helped. But there have a few more things to do: 1. if you have dir structure as: parent_dir => os_middile_dir => os.py, test.py. Then from test.py you can write "from .os import my_cwd" 2. Then goto parent_dir and run like: python -m os_middile_dir.test – Arun Aug 19 '22 at 00:27
  • yes, you should be able to do 1 and 2 provided that os_middile_dir is a python package, aka it include `__init__.py` – Copperfield Aug 19 '22 at 00:55
  • This workaround will work, but the actual problem posted has nothing to do with relative imports. It is specific to the `os` module which is special and always loaded when Python starts. If you try it with another package (e.g. `math`) simply writing `import math` will just work. – Selcuk Aug 19 '22 at 01:28
  • Thats true. my actual requirement was to bypass "os" module with my own os module. That is almost impossible I think. Still, I understood why I am unable to do it. Thanks for your time :) – Arun Aug 19 '22 at 07:01