Python 2 and Python 3

Changes in Python 3 compared to Python2.7

print a is no longer work in Python 3, always use print(a)

division by int can return float now

In python2.7:

1
2
>>> 5/2
2

while in python3

1
2
>>> 5/2
2.5

Some well-known APIs no longer return lists in Python 3

  • dict.iterkeys(), dict.iteritems() and dict.itervalues() are no longer supported in python3
  • xrange is replaced by range
  • zip(), map(), filter() returns an iterator.
1
2
3
4
5
6
7
8
9
10
11
>>> iter = zip([1, 2, 3], ['a', 'b', 'c'])
>>> next(iter)
(1, 'a')
>>> next(iter)
(2, 'b')
>>> next(iter)
(3, 'c')
>>> next(iter)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

For map() and filter(), we can use list(map()) to transform it to list.

Ordering function

All the elements to be sorted must be comparable to each other
cmp argument providing a comparison function is no longer supported

All strings are now Unicode by default in python 3

raw_input() is abandoned in Python 3 and use input() instead

Keyword only argument

In python 2

1
2
3
4
5
6
7
8
9
10
def delete(svy, question, delete_all=False):
if delete_all:
print("Deleted ALL questions from survey!")
else:
print("Deleted single question from survey.")
>>> delete(svy, question1) # Cool
Deleted single question from survey.

>>> delete(svy, question1, question2) # Not cool
Deleted ALL questions from survey!

while in Python 3, we can define keyword only argument:

1
>>> def delete(svy, question, *, delete_all=False):

then delete_all becomes keyword only argument

Metaclasses in Python3

1
2
3
4
5
6
7
>>> class FooBar:
pass
>>> type(FooBar)
<class 'type'>
>>> f = FooBar()
>>> type(f)
<class '__main__.FooBar'>
1
2
3
4
>>> isinstance(foo, Foobar)
True
>>> isinstance(Foobar, type)
True

These examples mean instance is an instance of a class, a class is an instance of metaclass. and type is a very useful metaclass in python.

  1. All classes and metaclasses including object are subclasses of object.
  2. All classes and metaclasses including type are instances of type.
  3. All objects including object are instances of object.

we can use type to create a class like this:

1
2
3
>>> MyClass = type('MyClass', (), {})
>>> MyClass
<class '__main__.MyClass'>

As type is a metaclass, so we can also create a custom metaclass that extens type

1
2
>>> class Meta(type):
... pass

Difference between _, and xx__ in Python

  • One underscore in the beginning marks a private method or attribute

  • Methods with two underscores in the beginning can not be overrided.

  • Methods with two underscores in the beginning and in the end are magic methods which only python can call.

Some useful methods are:
__call__, __new__, __init__, __prepare__

These four methods are very important for instance and class creation.

Python late binding

1
2
>>> [m(2) for m in (lambda: [(lambda x:i*x) for i in range(4)])()]
[6, 6, 6, 6]

The values of variables used in closures are looked up at the time the inner function is called. So as a result, when any of the functions returned by multipliers() are called, the value of i is looked up in the surrounding scope at that time. By then, regardless of which of the returned functions is called, the for loop has completed and i is left with its final value of 3. Therefore, every returned function multiplies the value it is passed by 3, so since a value of 2 is passed in the above code, they all return a value of 6 (i.e., 3 x 2).

References

https://stackoverflow.com/questions/101268/hidden-features-of-python
https://medium.com/instamojo-matters/become-a-pdb-power-user-e3fc4e2774b2#.1egkm87sm