2

My directory structure is:

package_name/
  __init__.py
  script.py
  time.py

I'm trying to import time (the built-in package) from script.py. however, my sibling time.py is hooked up instead.

What's the syntax of importing a package globally? (e.g. importing from /usr/lib/python2.7/dist-packages)

  • In c# i know it as the global:: prefix, what's the equivalent in python?
Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
  • 4
    There isn't one, rename your script. – jonrsharpe Jul 20 '15 at 19:26
  • 1
    possible duplicate of [python: importing from builtin library when module with same name exists](http://stackoverflow.com/questions/6031584/python-importing-from-builtin-library-when-module-with-same-name-exists) – BartoszKP Jul 20 '15 at 19:27

2 Answers2

2

Be more explicit with your imports. import time will import the python time module. from mypackage import time will import the time module in your mypackage package.

import time should never import mypackage.time

That said, don't shadow python built-in names, it's a bad habit and leads to these headaches later.

  • That's frustrating advice when python adds features that shadow names we already have – Greg Apr 28 '20 at 05:00
2

A Hack

While there are other ways, i adopted this one

1) add a sub package

Let's call it utils. your directory tree should look like:

package_name/
  __init__.py
  script.py
  time.py

  utils/
      __init__.py

2) create a file named builtin.py under that package

This should be the contents of builtin.py :

import time
time = time

3) use it!

Import time in script.py using this:

from utils.builtin import time

time.sleep(5)
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129