Grammar features added from Python3.6

Python3.6.0 was released on December 23, 2016, with some new updates. What’s New In Python 3.6

After all, for those who program using Python, the newly added grammatical functions may be of particular concern. So this time, it is a grammar function added in 3.6.0,

--PEP 498: Formatted string literal --PEP 515: Underscore in numeric literals --PEP 526: Variable annotation syntax --PEP 525: Asynchronous generator --PEP 530: Asynchronous comprehension

I will introduce about.

Formatted string literals (f-strings)

Python provides a format () method in the string (string) class, and you can use str.format () to perform variable substitution and value formatting. (In addition to this str.format (), there are% -formatting and string.Template as formatting and variable embedding methods.) However, the existing method is error-prone, inflexible, and has a problem in that it has to be written redundantly.

This time, f-strings is a function equivalent to format (), and its feature is that you can embed variables, formats, and executable expressions in __character strings __str.format () It's in __ where you don't have to write redundantly like .

Basic usage

You can declare f-strings with the string f'' prefixed with f, in which you use {} as a placeholder. An example is shown below.

python


#Basic variable expansion
hoge = 'hogehoge'
f'string value: {hoge}'  #=> 'string value: hogehoge'

In str.format (), what was written as follows can now be written as above.

python


'string value: {hoge}'.format(hoge='hogehoge')

I'll show you how to use it in various ways, but it's attractive that f-strings can be written in a simplified way because .format (...) can be omitted. (I'm very grateful that I was often angry at the line using str.format () because the code style evaluation of PEP8 exceeded 80 characters.)

Various usages

The variables you want to expand can be nested within {}, and you can use the expanded values to specify the format.

python


#Format
float_val = 0.123456
size = 4
f'result: {float_val:.{size}}'  #=> 'result: 0.1235'

Since it is evaluated as an execution expression in {}, you can expand the list and dictionary, add and subtract, etc. as follows.

python


#list
some_list = ['foo', 'bar', 'baz']
f'list item: {some_list[0]}'  #=> 'list item: foo'

#dictionary
some_dict = {'foo': 'foofoo', 'bar': 'barbar'}
f'dict item: {some_dict["foo"]}'  #=> 'dict item: foofoo'

# operation
some_value = 10
f'add ops: {some_value + 20}'  #=> 'add ops: 30'

f'list length: {len(some_list)}'  #=> 'list length: 3'

You can also call a function inside {}.

python


# function
def multi(a, b):
    return a * b

x = 10
y = 20
f'multi value: {multi(x, y)}'  #=> 'multi value: 200'

{} Can be broken because it is enclosed in implicit parentheses before evaluation.

python


class Foo(object):

    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

f'''Instance method call: {Foo("foo").get_name(
	)}'''
#=> 'Instance method call: foo'

You can get escaped output by using fr instead of f as the prefix.

# raw f-strings
fr'raw output\n'  #=> 'raw output\\n'

-PEP 498: Formatted String Literal

Underscore in numeric literals

It's a small addition, but you can now use underscores _ for numeric literals. However, the underscore position cannot be used at the beginning, end, or contiguous form, and can be placed between numbers or after the radix specifier. Certainly, if it continues with 000000 ..., it may be a little hard to see, but it seems that it will be solved.

#Decimal number
decimal = 10_000_000.0
print(decimal)  #=> 10000000.0

#Hexadecimal
hexadecimal = 0xCAFE_F00D
print(hexadecimal)  #=> 3405705229

#Binary number
binary = 0b_0011_1111_0100_1110
print(binary)  #=> 16206

# binary string => int casting
binary_string = int('0b_1111_0000', 2)
print(binary_string)  #=> 240

-PEP 515: Underscore in numeric literals

Variable annotation syntax

The type hinting feature added in PEP484 (Python 3.5) provides type hinting syntax for function parameters. Was being done. What was added in this PEP526 is the type hinting syntax for variables. "Variables" include class variables and instance variables in addition to regular variables.

python


from typing import List

vectors: List[float] = [0.1, 0.2]

counts: Dict[str, int] = {
    'foo': 10,
    'bar': 20,
    'baz': 30,
}

#Class variables are also available
class Foo(object):

    name: str = 'foo'

By the way, these annotations are not affected by the result of this annotation in the Python interpreter, so there is no warning on the Python runtime. This feature is now a third party tool (eg mypy, pytype, [PyCharm] You need to know that (https://www.jetbrains.com/pycharm/ etc.) is a feature that makes it easy to reference annotation attributes.

url: str = ''

url = 100  #=>

print(url)  #=>Displayed as 100 without warning etc.

-PEP 526: Variable Annotation Syntax

Asynchronous generator

The async / await syntax added in PEP492 (Python 3.5) does not allow ʻawaitandyield to be used for the same function. However, since 3.6, there is support for asynchronous generators where ʻawait and yield can be used for the same function.

python


import asyncio


async def ticker(delay, to):
    for i in range(to):
        yield i
        await asyncio.sleep(delay)


async def run():
    async for i in ticker(1, 10):
        print(i)


loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(run())
finally:
    loop.close()

-PEP 525: Asynchronous Generator

Asynchronous inclusion notation

Starting with 3.6, the use of ʻasync for` in list, set, dictionary comprehensions and generator expressions is supported. It's a small change, but I think it's easier to write.

python


import asyncio


async def aiter():
    n = 10
    for i in range(n):
        yield i
        await asyncio.sleep(0.5)

#Asynchronous inclusion notation
async def run():
    result = [i async for i in aiter() if i % 2]
    print(result)

#Run above()Same syntax as
async def run():
    result = []
    async for i in aiter():
        if i % 2:
            result.append(i)


loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(run())
finally:
    loop.close()

-PEP 530: Asynchronous comprehension


As mentioned above, I would definitely like to use it in an environment where compatibility is not a concern.

This time, I introduced only the grammar change, but from 3.6, there are others.

--Keeping the order of keyword arguments --Maintaining the order of class attribute definitions -secrets Addition of modules

There are changes such as. For details, please refer to What ’s New In Python 3.6.

Recommended Posts

Grammar features added from Python3.6
python grammar check
sql from python
MeCab from Python
Python grammar notes
Python3 basic grammar
Touch MySQL from Python 3
Python basic grammar / algorithm
Operate Filemaker from Python
Python ~ Grammar speed learning ~
Access bitcoind from python
Changes from Python 3.0 to Python 3.5
Extract features (features) from sentences.
Changes from Python 2 to Python 3.0
Python from or import
Use MySQL from Python
Run python from excel
Install python from source
Execute command from Python
Python basic grammar (miscellaneous)
Operate neutron from Python!
Use MySQL from Python
Operate LXC from Python
Python basic grammar note (4)
Manipulate riak from python
Python basic grammar note (3)
Force Python from Fortran
Use BigQuery from python.
Python basic grammar memo
Execute command from python
[Python] Read From Stdin
Use mecab-ipadic-neologd from python
Flatten using Python yield from
Call CPLEX from Python (DO cplex)
Basic Python 3 grammar (some Python iterations)
Post from Python to Slack
Cheating from PHP to Python
Make MeCab available from Python3
Information obtained from tweet_id (Python)
OCR from PDF in Python
Run illustrator script from python
Use MySQL from Anaconda (python)
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Study from Python Hour4: Object-oriented ②
Query Athena from Lambda Python
Access Oracle DB from Python
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Study from Python Hour3: Functions
Start / stop GCE from python
Python basic grammar (miscellaneous) Memo (3)
Stop Omxplayer from Python code
Switch from python2.7 to python3.6 (centos7)
Python basic grammar (miscellaneous) Memo (2)
Connect to sqlite from python
Basic Python grammar for beginners
Install pyenv from Homebrew, install Python from pyenv
Study from Python Hour4: Object-oriented ①
Python naming convention (from PEP8)
Get started with Python! ~ ② Grammar ~
[Python] Sample code for Python grammar