Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34237

python import package globally

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)

Upvotes: 2

Views: 3054

Answers (2)

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34237

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)

Upvotes: 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.

Upvotes: 2

Related Questions