Here are some grammars that you might get a slapstick face if you know it in Python

I will introduce the python grammar that you may be able to face if you know mainly the new functions.

1. Substitution formula

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/

2. Comprehensions other than lists

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

3. Type hint

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

  1. dataclass It is a data object added from python3.7. This is a doya face function that is useful when defining an interface when developing a web system. It's a feature I like at a level where you can update to python3.7 to use it. --Declare a class with a @ 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

5. f string

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

Summary

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

Here are some grammars that you might get a slapstick face if you know it in Python
What to do if you get a minus zero in Python
BigQuery-If you get a Reason: responseTooLarge error in Python
If you encounter a "Unicode Decode Error" in Python
Understand Python yield If you put yield in a function, it will change to a generator
Why do you add a main ()-if statement in Python?
If you write TinderBot in Python, she can do it
If you think that the person you put in with pip doesn't work → Maybe you are using python3?
If you know Python, you can make a web application with Django
If you get Error: That port is already in use. In Django
If you get stuck in Cannot load mkl_intel_thread.dll in Python on Windows
Delete a particular character in Python if it is the last
If you want to assign csv export to a variable in python
Check if you can connect to a TCP port in Python
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
If you want a singleton in python, think of the module as a singleton
If you get a Programming Error: (1146, "Table'<table name>' doesn't exist") in Django
I made a Discord bot in Python that translates when it reacts
What happens if you do "import A, B as C" in Python?
If you get a no attribute error in boto3, check the version
A memorandum of filter commands that you might forget in an instant
How to get a stacktrace in python
Get a token for conoha in python
What to do if you get a "No versions found" error in pipenv
A solution if you accidentally remove the python interpreter in / usr / local / bin /.
Create a plugin that allows you to search Sublime Text 3 tabs in Python
[Beginner] What happens if I write a program that runs in php in Python?
If you guys in the scope kitchen can do it with a margin ~ ♪
Linux command that can be used from today if you know it (Basic)
What to do if you get "Python not configured." Using PyDev in Eclipse
[Python] What to check when you get a Unicode Decode Error in Django
Even if you are a beginner in python and have less than a year of horse racing, you could win a triple.