11/29/2018

Python Notes (1)

1. Python FAQ:
https://docs.python.org/2.7/faq/programming.html

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

If you do an "import syslib", how does the python locate the library?


1. local directory <<<< surprised?!

2. PYTHONPATH

so if you have a locally mistaken syslib.py or syslib.pyc under the local directory, you gonna break this import. And if you see something wanky, print cmd.__file__ will be helpful (or cmd.__version__)


3. Python Set
https://docs.python.org/3/tutorial/datastructures.html#sets
  • {} and set() can be used to create set
  • But to create an empty one, must use set(), not {} which is to create a dictionary. 
  • set_ = {0}
4. 3 Ways to delete an element in a list
1) most efficient - del List[idx]
2) less efficient if need to have the element - List.pop(idx)
3) lest effificient - slice, List[:i] + List[i+1:]

5. Python reduce, filter
>>> l = [1,2,3,4]
>>> reduce( (lambda x,y: x*10+y), l)
1234
>>> reduce( (lambda x,y: x*100+y), l)
1020304
>>> l = range(1, 100, 5)
>>> l
[1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]
>>> filter(lambda x:x%4, l)

[1, 6, 11, 21, 26, 31, 41, 46, 51, 61, 66, 71, 81, 86, 91]

6. Python Naming Convention

http://legacy.python.org/dev/peps/pep-0008/#code-lay-out
  • limit all lines to 79,docstring/comment to 72
class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight &gt; 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

  • Module: short, 
    • all-lower-case name, like pystock.py
  • Class: CapWords, like 
    • StockHist, StockInfo, StockERHist
  • Function: 
    • lower_case_with_underscore
  • Method and instance: 
    • lower_case_with_underscore
  • Constants: 
    • ALL_CAPITALS_WITH_UNDERSCORE
  • Internal attribute: 
    • _single_leading_underscore
    • NOT imported. 
  • empty sequence = FALSE, so 
    • YES: if not seq:... 
    • NO: if len(seq)
  • Attributes: 
    • self.lower_case_with_underscore



No comments:

Post a Comment