Month: March 2016

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.

https://docs.python.org/2/tutorial/modules.html#the-module-search-path

2  Why absolute import?  what is aboslute import? cited from PEP 0328( https://www.python.org/dev/peps/pep-0328/#relative-imports-and-name)

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:

http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time

http://stackoverflow.com/questions/33743880/what-does-from-future-import-absolute-import-actually-do

http://programmers.stackexchange.com/questions/159503/whats-wrong-with-relative-imports-in-python

A final explanation: https://docs.python.org/2.5/whatsnew/pep-328.html

4.

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)

http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/

http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value

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

list(month)

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

Scenario:

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

Solution:

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”:

http://www.markbetz.net/2014/04/30/re-raising-exceptions-in-python/ http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html http://stackoverflow.com/questions/14503751/how-to-write-exception-reraising-code-thats-compatible-with-both-python-2-and-p


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

4
4
4
4
4

> 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()
4
4
4
4
4

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

>>>
>>> create_multipliers()
0
1
2
3
4
>>>

http://code.activestate.com/recipes/502271/

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. http://stackoverflow.com/questions/4020419/why-arent-python-nested-functions-called-closures

http://www.shutupandship.com/2012/01/python-closures-explained.html

 

 

 

 

 

 

 

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)

Reference:

http://www.cnblogs.com/zuoyuan/p/3777422.html

http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array.html

Related:

Search  for a range

http://blog.allenzhao.com/leetcode/2014/09/15/LeetCode-Search-for-a-range/

http://bangbingsyb.blogspot.com/2014/11/leecode-find-minimum-in-rotated-sorted.html

http://yucoding.blogspot.com/2014/10/leetcode-question-find-minimum-in.html