I will introduce the python grammar that you may be able to face if you know mainly the new functions.
New syntax added from python3.8. It's good to know something new.
The assignment expression is written in the syntax : =
, and the conditional expression and the assignment statement can be used at the same time.
For example, the following common conditional expressions
text = 'Hello New Expression!!'
text_length = len(text)
if text_length > 10:
print(f"String is too long!!({text_length} length, expected <= 10)")
It can be abbreviated as follows using : =
.
You can see that ʻif (text_length: = len (text))> 10: `plays both assignment and conditional expressions.
text = 'Hello New Expression!!'
if (text_length := len(text)) > 10:
print(f"String is too long!!({text_length} length, expected <= 10)")
refs Substitution expression: https://www.python.org/dev/peps/pep-0572/
I think a common comprehension is to generate a list like this:
numbers = [1,2,3]
dubble_numbers = [x*2 for x in numbers]
print(dubble_numbers)
#[2, 4, 6]
Although rarely used, there are also dictionary, set, and generator comprehensions. This is a doya face point.
--Dictionary comprehension
If you write a key-value like x: x * 2
in{}
, a dictionary will be generated.
numbers = [1,2,3]
dubble_number_dict = {x:x*2 for x in numbers}
print(dubble_number_dict)
#{1: 2, 2: 4, 3: 6}
--Set comprehension
If you write only value in {}
like x
, a set will be generated.
numbers = [1,2,3,1,1]
dubble_number_set = {x for x in numbers}
print(dubble_number_set)
# set([1, 2, 3])
--Generator type
If you write in ()
like a list comprehension, a generator will be generated instead of tuple.
numbers = [1,2,3]
dubble_number_generator = (x for x in numbers)
print(dubble_number_generator)
# <generator object <genexpr> at 0x10d7779b0>
refs Data structure: https://docs.python.org/3.9/tutorial/datastructures.html
Starting with python3.5, it is possible to declare (annotate to be exact) types in code like a statically typed language. I feel like I'm abandoning the merits of dynamically typed languages, but when it comes to complicated development, I think that many people are conservatively anxious if the types are not explicitly declared. Precautions when using --No error occurs even if you assign a different type with the same value as commented out. --Since the standard function does not have a type check function, it can be used together with the tool. It would be nice if you could explain this area with a sloppy face.
The specific source code is as follows.
Maintainability is improved, but it is an extension of comments and is not checked at runtime.
text: str = 123 # Assignment int
also passes without error.
def greeting(name: str) -> str:
return f'Hello {name}'
text: str = 'Python!!'
print(greeting(text))
# Hello Python!!
text: str = 123 # Assignment int
print(greeting(text)) # No error
# Hello 123
Check tools are not provided by default, so you need to use an external tool.
Probably the most famous is mypy
. http://www.mypy-lang.org/
There are various other rules such as how to declare user-defined classes with type hints, but I will omit them here.
refs: Type hint: https://docs.python.org/3.9/library/typing.html
@ dataclass
decorator.
--Simplified redundant writing using special methods such as __init__
. (Correctly, the decorator creates a special method)A concrete usage example is as follows.
from dataclasses import dataclass,asdict,astuple
@dataclass
class Person:
name: str
age: int = 0
def greeting(self) -> str:
return f"My name is {self.name}, {self.age} years old."
tanaka = Person('tanaka',18)
print(tanaka.greeting())
# My name is tanaka, 18 years old.
baby = Person('taro') # Use default value
print(baby.greeting())
# My name is taro, 0 years old.
print(asdict(baby)) # To dict object
# {'name': 'taro', 'age': 0}
print(astuple(baby)) # To tuple object
# ('taro', 0)
There are also functions such as making it an immutable object and extending the initialization process with __post_init__
, but it is omitted here.
refs: dataclass: https://docs.python.org/3/library/dataclasses.html
This is a string template added from python3.6.
It is simpler and more sophisticated than the previous string methods format ()
and % operator
.
Specifically, put f" "
at the beginning of the character string and use it as follows.
a,b = 1000,2000
print(f'a is {a},b is {b}')
# a is 1000,b is 2000
print(f'sum of ab is {a+b}') # can be calculated
# sum of ab is 3000
print(f'a: {a:,}') # separated by comma
# a: 1,000
As mentioned above, the point that calculation in the character string is possible and the point that flexible formatting is possible are the points that can be ridiculed.
Also, since python3.8, the function has been extended for debugging variables.
a,b = 1000,2000
print(f'a={a},b={b}') # before 3.8
# a=1000,b=2000
print(f'{a=},{b=}') # after 3.8
# a=1000,b=2000
By inserting =
after the variable, you can see that both the value and name of the variable are output.
refs: Format: https://docs.python.org/3/tutorial/inputoutput.html Debugging possible: https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging
When I work in the field, I think that it is difficult to use it because past debts such as python2 remain, and I want to repair it with a sloppy face while being excited about new functions.
Recommended Posts