Thursday, August 31, 2017

python function decorators

https://realpython.com/blog/python/primer-on-python-decorators/

https://www.thecodeship.com/patterns/guide-to-python-function-decorators/

https://www.learnpython.org/en/Decorators

decorators dynamically alter the functionality of a function, method, or class

This is ideal when you need to extend the functionality of functions that you don't want to modify.

Things to know for understanding the decorators:

- assign function to a variable:
def f():
    print 'ok'

a = f
a()

- define function inside other function (sub function in a function, and the sub function is called):
- Function as parameter:
def a():
    return 'HELLO'

def b(fun):
    return str(fun()) + 'HI;

b(a)







range and xrange

http://www.geeksforgeeks.org/range-vs-xrange-python/


range() – This returns a list of numbers created using range() function.
xrange() – This function returns the generator object that can be used to display numbers only by looping. Only particular range is displayed on demand and hence called “lazy evaluation“.

memory used for xrange is much less compared to range


python control flow if elif else

a = 5
>>> a=7
>>> if a==5: print 5
... elif a==6: print 6
... else: print 0
...
0
>>> a=7
>>> if a==5: print 5
... elif a==6: print 6
... elif a==7: print 7
... else: print 0
...
7
>>> a=8
>>> if a==5: print 5
... elif a==7: print 7
... elif a==6: print 6
... else: print 0
...
0

search in python

http://www.python-course.eu/re.php

https://stackoverflow.com/questions/180986/what-is-the-difference-between-pythons-re-search-and-re-match

https://stackoverflow.com/questions/13423624/extract-string-with-python-re-match

basic regular expression use:
re.match("ab", "abc").group()


Note that match may differ from search even when using a regular expression beginning with '^''^' matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The “match” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it.

# match is faster: it always/only searches from the beginning of a string.  This fixed criteria makes the search faster.


using 'in' for search

http://www.python-course.eu/re.php

s = "hi man"
"man" in s => True