sffjunkie
sffjunkie

Reputation: 52

Python absolute imports on OSX

Which of the following Python 2.7 import scenarios are correct? i.e. if I have a module with a name shadowing a stdlib module should import <module> import the stdlib or the local version?

On Linux

$ ls
__init__.py  time.py

~/tmp $ cat time.py 
def a():
  print(¨a¨)

~/tmp $ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> dir(time)
['__doc__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime',     'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']

and on OSX

sdk$ ls
__init__.py time.py     time.pyc

$ cat time.py
def a():
  print("a")

$ python
Python 2.7.6 (default, Apr  9 2014, 11:48:52) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> dir(time)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a']

PS: Windows seems to follow Linux and using from __future__ import absolute_import has no effect

Upvotes: 0

Views: 110

Answers (1)

vlad-ardelean
vlad-ardelean

Reputation: 7622

Your current path will usually be appended in the first position of the list sys.path. That means you'll always import your custom module.

If you don't want that, then you could try starting the interpreter in python -E mode. That doesn't add the current path the sys.path and you'll have your default module being loaded.

Another way to import the global module is to do a little hack

import os

temp_path = os.getcwd()
os.chdir('/some/other/path')

import myshadowingmodule
os.chdir(temp_path)

This makes it seem you're in a different directory when importing, and after importing, brings you back to where you were

Also there's 2 functions __import__ and importlib.import_module - in case you were wondering, you can't use them to import the shadowed module.

Upvotes: 1

Related Questions