Little-known Python language specification (compatible with Python 3.4 or later)

Introduction

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.

Beginner's edition

Complex literal

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)

Comprehension including multiple for..in

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]

Every n slices

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]

Copying the list by slicing

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

Intermediate

Ellipsis

... is treated as an object that represents "abbreviation". For more information, see here.

>>> ...
Ellipsis
>>> bool(...)
True

Keyword-limited arguments

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)
>>>

Function annotation

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)

Advanced edition

Decorator with arguments

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.

Class decorator

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

reference

Recommended Posts

Little-known Python language specification (compatible with Python 3.4 or later)
100 Language Processing with Python Knock 2015
Python 3.4 or later standard pip
Ruby's `` like Python. 2.6 or later
Update Python for Raspberry Pi to 3.7 or later with pyenv
100 Language Processing Knock with Python (Chapter 1)
100 Language Processing Knock with Python (Chapter 3)
10 functions of "language with battery" python
Multi-line size specification reading with python
Master the type with Python [Python 3.9 compatible]
Blender 2.82 or later + python development environment notes
100 Language Processing Knock with Python (Chapter 2, Part 2)
3. Natural language processing with Python 2-1. Co-occurrence network
3. Natural language processing with Python 1-1. Word N-gram
I tried a functional language with Python
100 Language Processing Knock with Python (Chapter 2, Part 1)
[Python] Let's make matplotlib compatible with Japanese
Try assigning or switching with Python: lambda
Getting started with Python with 100 knocks on language processing
3. Natural language processing with Python 2-2. Co-occurrence network [mecab-ipadic-NEologd]
Python> 3.14_1592_6535_8972> PEP515 (Python v3.6 or later possible writing style)
[Python] I played with natural language processing ~ transformers ~
Run pip install on MacOS Python 3.7 or later
Install vim7.3 (+ python2.4) from source (compatible with Gundo.vim)
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
Zundokokiyoshi with python
Excel with Python
Microcomputer with Python
Cast with python
Easy scraping with Python (JavaScript / Proxy / Cookie compatible version)
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
[Chapter 5] Introduction to Python with 100 knocks of language processing
3. Natural language processing with Python 4-1. Analysis for words with KWIC
Building an environment for natural language processing with Python
Pretty print json or yaml with color in python
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
Get in touch with functional programming in JavaScript or Python 3
[Chapter 4] Introduction to Python with 100 knocks of language processing