Friday, May 6, 2016

The Top 20 Hidden Features of Python

>Just A summary of the hidden possibilities.
>I will explain them in the following Posts


  • Braces
from __future__ import braces

  • List slicing
a = [1,2,3,4,5,6]
a[2:4]
[3,4]
a[2:]
[3,4,5,6]
a[:2]
[1,2]
a[::]
[1,2,3,4,5,6]


  • For .. else Syntax
for i in sfoo:
    if bar(i):
        #do something
        break
else:
    return -1

  • Yield statement
def primes(numb):
     while True:
         if isprime(numb):
              yield numb
         numb+=1

  • Multiple assignments
 a, b   = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2

  • Argument unpacking
def aMethod(arg1, arg2):
    # Do something

foo = (3, 4)
bar = {'y': 3, 'x': 2}

aMethod(*point_foo)
aMethod(**point_bar)

  • Decorators
def print_arguments(function):
     def wrapper(*args, **kwargs):
         print 'Arguments:', args, kwargs
         return function(*args, **kwargs)
     return wrapper


@print_args
    def write(text):
        print text

  • 'this' Module
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

  • Descriptors
class Property(object):
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, obj, type):
        if obj is None:
            return self
        return self.fget(obj)
class MyClass(object):
    @Property
    def foo(self):
        return "Foo!"

  • Docstring Tests

  • Elipse slicing Syntax
>>> class C(object):
...  def __getitem__(self, item):
...   return item
... 
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)

  • Enumeration
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> for index, item in enumerate(a): print index, item
...
0 a
1 b
2 c
3 d
4 e

  • Generator Expressions
>>>x = [n for n in foo if bar(n)]

  • In place value swaping
>>>a, b = b, a

  • Multi-Line Regex
>>>> pattern = """
... ^                   # beginning of string
... M{0,4}              # thousands - 0 to 4 M's
... (CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
...                     #            or 500-800 (D, followed by 0 to 3 C's)
... (XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
...                     #        or 50-80 (L, followed by 0 to 3 X's)
... (IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
...                     #        or 5-8 (V, followed by 0 to 3 I's)
... $                   # end of string
... """
>>> re.search(pattern, 'M', re.VERBOSE)

  • Named string formatting
print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42}
The answer is 42.


  • New Types at runtime
>>> NewType = type("NewType", (object,), {"x": "hello"})
>>> n = NewType()
>>> n.x
"hello"


  • try exepet & else
try:
#Something to Try
Except(#Excetion):
#Do something
else:
#Do sth other
finally:
#Do always

  • .pth files
  • with statement
from __future__ import with_statement

with open('foo.txt', 'w') as f:
    f.write('hello!')


No comments:

Post a Comment