2

I have a Python package called mylib that has a module inside named os:

mylib
|- __init__.py
|- os
   |- __init__.py
   |- makedirs.py

Now when I import mylib, its __init__.py gets called:

from os import environ
from os.path import dirname, join, abspath

# then do something with the paths

Here I'm trying to use the builtin os, but my Python seems to think I want to use mylib's module os, hence throwing:

ImportError: No module named path

I know some people are against using the same names for custom names as standard built-in names, but I really think I should keep the name os, as it's the most intuitive and easy-to-remember name.

In this case, how do I let my Python know it should import the builtin os?

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • Did you try `from mylib import abc, xyd`? Only import whatever is required. – Yogesh Chuahan Jun 13 '19 at 18:00
  • If your package isn't going to be used only by yourself, `os` may be misleading to the others, keep that in mind. – asikorski Jun 13 '19 at 18:01
  • 1
    @GreenCloakGuy won't `mylib.os` still be cached in `sys.modules`? – C.Nivs Jun 13 '19 at 18:01
  • 1
    Why not do the simple thing and just rename your module? – rdas Jun 13 '19 at 18:02
  • Possible duplicate of [How to import a module given the full path?](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) – Green Cloak Guy Jun 13 '19 at 18:04
  • 1
    and figure out where python modules are saved on your computer, then import them by filepath. Really, the easiest way would be to rename your package - `os` might be a good name, but would `operating_system` or whatever else your `os` stands for be that bad? You can always alias it when you import it, e.g. `import operating_system as osm` – Green Cloak Guy Jun 13 '19 at 18:07
  • Please do yourself and others a favour, and *always* avoid using builtin or stdlib names for your modules and names. Otherwise you will get into trouble often. The worst errors are the silent ones (you get no errors but they are there). It happened to me. – progmatico Jun 14 '19 at 23:05

0 Answers0