Here's a summary of the lesser-known (and selfish) Python language specifications.
Beginner / intermediate / advanced classification is appropriate.
I will add if there are others.
Complex number operations can be performed as standard. The subscript uses j instead of i.
>>> c1 = 1 + 1j
>>> c2 = 1 - 2j
>>> c1 + c2
(2-1j)
>>> c1 * c2
(3-1j)
>>> c1 / c2
(-0.2+0.6j)
You can write multiple for..in in the comprehension.
>>> a = range(3)
>>> b = range(4)
>>> [x + y for x in a for y in b]
[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5]
You can retrieve elements such as lists every n by writing as follows.
>>> a = list(range(20))
>>> a[::2]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
You can make a copy of the list without passing an index to the slice syntax.
>>> a = range(10)
>>> b = a
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b is a #b and a are the same object
True
>>> c = a[:]
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> c is a #b and a are separate objects
False
Ellipsis
...
is treated as an object that represents "abbreviation".
For more information, see here.
>>> ...
Ellipsis
>>> bool(...)
True
By writing *,
in the function definition, you can make sure that the following arguments must be called as keyword arguments.
>>> def f(a, *, b):
... pass
...
>>> f(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: f() missing 1 required keyword-only argument: 'b'
>>> f(1,2)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1,b=2)
>>>
You can annotate function arguments and return values. Since it is an annotation for use in documents etc., no error will occur even if an object of a different type is given.
>>> def f(x : int, y : int) -> int:
... return x + y
...
>>> f(2, 3)
5
>>> f('hoge', 'fuga') #Does not cause an error
'hogefuga'
global
global
allows you to define global variables at runtime from any scope.
>>> def f():
... global a
... a = 1
...
>>> a #Here a is undefined
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'a' is not defined
>>> f() #The global variable a is defined by calling f
>>> a
1
nonlocal
nonlocal
allows assignment to a variable that belongs to the outer scope.
Closures are easy to make.
>>> def make_counter():
... count = 0
...
... def counter():
... nonlocal count
... count += 1
... return count
...
... return counter
...
>>> c = make_counter()
>>> c(), c(), c()
(1, 2, 3)
You can create a decorator with arguments by writing a "function that receives a function and returns a function".
Flask's @ route ('/')
etc. seems to be implemented using this.
>>> def greet(before, after):
... def decorator(func):
... def wrapper(*args, **kwargs):
... print(before)
... func(*args, **kwargs)
... print(after)
... return wrapper
... return decorator
...
>>> @greet('Hi.', 'Bye.')
... def introduce(name):
... print('I am ' + name + '.')
...
>>> introduce('yubessy')
Hi.
I am yubessy.
Bye.
You can write a decorator that wraps a class. The following is an implementation example of a simple singleton.
>>> def singleton(cls):
... instances = {}
... def getinstance(*args, **kwargs):
... if cls not in instances:
... instances[cls] = cls(*args, **kwargs)
... return instances[cls]
... return getinstance
...
>>> @singleton
... class C(object):
... pass
...
>>> c1 = C()
>>> c2 = C()
>>> c1 is c2
True
yield from
You can create a generator that returns values from other iterators.
>>> def g():
... yield from range(5)
... yield from range(5, 10)
...
>>> [i for i in g()]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
raise from
Keep the sender's exception when chaining exceptions.
>>> try:
... raise Exception('e1') from Exception('e2')
... except Exception as e:
... print(e.__cause__)
...
e2
Recommended Posts