Category: Programming

Python relative import and absolute import

1. when we do import, where does it search ?

it depends if you are using relative import or absoluate import.

in python 2, relative import is by defaut.  however, we can make absolute import to be default by adding “from __future__ import absolute_import” at the first line of the file.

in python 3, absolute import is by default.  and if we want to use relative import, we need to be explicit (by having a leading dot in the ‘from import’  ).   Relative imports must always use from <> import ; import foo as a bare term will always be an absolute import.import <> is always absolute. Of course, absolute imports can use from <> import by omitting the leading dots. The reason import .foo is prohibited.

when realtive import is by default (in python 2),  it will first try to find the target in the current directory. then it will go to search in the python path (sys.path). Therefore, Imports can be ambiguous in the face of packages; within a package, it’s not clear whether import foo refers to a module within the package or some module outside the package. (More precisely, a local module or package can shadow another hanging directly off sys.path .) the solution is to use absolute import, searching sys.path only.

 sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

2  Why absolute import?  what is aboslute import? cited from PEP 0328(

Rationale for Absolute Imports

In Python 2.4 and earlier, if you’re reading a module located inside a package, it is not clear whether

import foo

refers to a top-level module or to another module inside the package. As Python’s library expands, more and more existing package internal modules suddenly shadow standard library modules by accident. It’s a particularly difficult problem inside packages because there’s no way to specify which module is meant. To resolve the ambiguity, it is proposed that foo will always be a module or package reachable from sys.path . This is called an absolute import.

In python 3 (or after we add “from __future__ import absolute_import”)

Relative imports must always use from <> import ; import <> is always absolute. Of course, absolute imports can use from <> import by omitting the leading dots. The reason import .foo is prohibited is because after


3.  what is relative import?

Note relative import is only possible in package.

Relative imports use a module’s name attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to ‘main’) then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

reference about relative import:

A final explanation:


Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

Sorting dict using sorted() in python

sorted(iterable, key, reverse)

month = {“one”: “January”, “two”: “February”, “three”: “March”}


sort dict kesy: sorted(month)

sort dict values: sorted(month.values())

sort dict keys using dict values:  sorted(month, key=month.__getitem__)

sort the values in month by its keys: [value for key, value in sorted(month.items())]


sort a dict by value:

dict(sorted(month.items(),  key=operator.itemgetter(1)))

sort a dict by value:

dict(sorted(month.items(),  key=operator.itemgetter(0)))



How to rethrow exception in Python without losing the original traceback


catch an exception in one place, and raise it again in another.


when the original exception was caught:

exc_info = sys.exc_info()

In a difference place, we get the reference to the exc_info stored above:

In Python  2:

raise exc_info[0], exc_info[1], exc_info[2]

In Python 3:

       raise exc_info[0].with_traceback(exc_info[1], exc_info[2])

When should we use “raise e?” here ‘e’ is an exception that you’ve just caught, Never. Doing so will always lose the traceback information from the previous frames on the stack, and obfuscate the point of origin of the original error.

See the difference between “raise e” and “raise”:

Understanding Python closure

>> def create_multipliers():
…     return [lambda x : i * x for i in range(5)]

>>> for multiplier in create_multipliers():
…   print multiplier.__closure__[0].cell_contents


> def create_multipliers():
…    result = [lambda x : i * x for i in range(5)]
…    for fun in result:
…       print fun.__closure__[0].cell_contents

>>> create_multipliers()

>> def create_multipliers():
…    result=[]
…    for i in range(5):
…       result.append(lambda x: i*x)
…       print result[i].__closure__[0].cell_contents

>>> create_multipliers()

A CLOSURE is a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory. If you have ever written a function that returned another function, you probably may have used closures even without knowing about them.

so only if a function is trying to access a variable form an enclosing scope, it is called a closure.








Search in Rotated Sorted Array解答


the key is to locate the range which satisfy if x<y then array[x] < array[y].

then we can decide if the element is within [x,y] or outside of [x,y], narrowing down the search space by roughly half.

If there is duplicate (array[middle] == array[right],  then we can’t decide whether to throw away [x,y] entirely or jump into [x,y]. A solution is to only remove array[right] (right -=1)



Search  for a range