>Just A summary of the hidden possibilities.
>I will explain them in the following Posts
from __future__ import braces
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 i in sfoo:
if bar(i):
#do something
break
else:
return -1
def primes(numb):
while True:
if isprime(numb):
yield numb
numb+=1
a, b = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2
def aMethod(arg1, arg2):
# Do something
foo = (3, 4)
bar = {'y': 3, 'x': 2}
aMethod(*point_foo)
aMethod(**point_bar)
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
>>> 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!
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!"
>>> class C(object):
... def __getitem__(self, item):
... return item
...
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)
>>> 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
>>>x = [n for n in foo if bar(n)]
>>>a, b = b, a
>>>> 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)
print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42}
The answer is 42.
>>> NewType = type("NewType", (object,), {"x": "hello"})
>>> n = NewType()
>>> n.x
"hello"
try:
#Something to Try
Except(#Excetion):
#Do something
else:
#Do sth other
finally:
#Do always
from __future__ import with_statement
with open('foo.txt', 'w') as f:
f.write('hello!')