Useful Python built-in functions that you use occasionally

This article is the 19th day article of Takumi Akashiro Alone Advent Calendar 2020.

At the beginning

On Saturday, I made an AE script for practice! I was thinking of using the material I had in stock, When I looked it up before writing the article, I found that the same thing could be done with the standard functions of AE, and I was completely lost. Instead, I'll write about the Python built-in functions that I use occasionally.

To be honest, it is useful to read the Official Documents every 10 minutes per function every day. Let's read everyone! Official documentation!

Python built-in functions

zip(*iterables)

Create an iterator that collects elements from each iterator. From Built-in Functions — Python 3.9.1 Documentation

>>> src_paths = ["c:/nanka", "c:/unagi", "c:/ankimo"]
>>> dst_paths = ["d:/nanka", "f:/unagi", "e:/ankimo"]
>>> 
>>> list(zip(src_paths, dst_paths))
[('c:/nanka', 'd:/nanka'), ('c:/unagi', 'f:/unagi'), ('c:/ankimo', 'e:/ankimo')]
>>> 
>>> dst_files = ["ohagi", "ooiwa", "karasumi"]
... for src_path, dst_path, dst_file in zip(src_paths, dst_paths, dst_files):
...     print(src_path, dst_path, dst_file)
c:/nanka d:/nanka ohagi
c:/unagi f:/unagi ooiwa
c:/ankimo e:/ankimo karasumi

I use it quite often. It may not be included in the occasional use, but If you don't know it, you can call it without knowing it, so I will introduce it this time.

Personally, I like the combination of zip () and dict (), dict (zip (keys, values)).

sorted(iterable, *, key=None, reverse=False) Sorts iterable objects and returns them as list. No, I'm sure some people know that, but this time I would like to introduce the key argument. You can pass a function with one argument to key. It means that you can sort using the result.

>>> sorted(["A", "a", "d", "B"])
['A', 'B', 'a', 'd']
>>> sorted(["A", "a", "d", "B"], reverse=True)
['d', 'a', 'B', 'A']
>>> 
>>> sorted(["A", "a", "d", "B"], key=str.lower)
['A', 'a', 'B', 'd']
>>> 
>>> sorted(["A", "a", "d", "B"], key=lambda x: {"A": 99, "a": 0, "d": 3}.get(x, 100))
['a', 'd', 'A', 'B']
>>> 
>>> sorted({"onaka": 2, "udon": 0}.items(), key=lambda item: item[1])
[('udon', 0), ('onaka', 2)]

As you can see in the example, it can be used in cases where you want to sort by the value on the value side when you change the dictionary to list.

hasattr(object, name) Make sure the object has an attribute named name.

>>> import datetime

>>> class SampleClass(object):
...     # __init__Is not implemented, so it is omitted.
...     def print_sample(self):
...         if not hasattr(self, "_text"):
...             print("Generate!")
...             self._text = str(datetime.datetime.now())
...         print(self._text)
...
>>> sample = SampleClass()
>>> sample.print_sample()
Generate!
2020-12-19 23:16:19.197768
>>> sample.print_sample()
2020-12-19 23:16:19.197768
>>> sample.print_sample()
2020-12-19 23:16:19.197768

~~ Personally, a convenient function for generating fucking code ~~ It is used when you want to check if an instance variable has already been defined and initialize it if it has not been defined.

It's convenient, but if you don't know the TPO, it will reduce maintainability. Do you use it only when you want to make a singleton-like pattern?

globals()

Returns a dictionary representing the current global symbol table. This is always a dictionary of the current module (in a function or method, the module that defines it, not the module that called it). From Built-in Functions — Python 3.9.1 Documentation

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__spec__': None, '__annotations__': {},'__builtins__': <module 'builtins' (built-in)>}
>>> import sys
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
'sys': <module 'sys' (built-in)>}

You can use globals () in Maya's Script Editor to get the objects declared in the interpreter. So, did you import that module? Hit when you think. I usually import it before hitting it.

id(object) A function that returns the id of an object. Objects with the same id are the same. (Of course)

The is comparison of hoge is huga is comparing this id.

>>> sample_str_a = "apple"
>>> sample_str_b = "apple"
>>> 
>>> print(id(sample_str_a) == id(sample_str_b), id(sample_str_a), id(sample_str_b))
True 1289401480176 1289401480176
>>> 
>>> sample_str_a += " pie"
False 1289401480240 1289401480176
#str type+=Then it returns another object.
>>> 
>>> sample_list_a = []
>>> sample_list_b = []
>>> 
>>> sample_list_a == sample_list_b
True
>>> sample_list_a is sample_list_b
False

>>> print(id(sample_list_a) == id(sample_list_b), id(sample_list_a), id(sample_list_b))
False 1289401452736 1289401452800
>>> #Same result as is
>>> 
>>> sample_list_c = sample_list_d = []
>>> sample_list_c += ""
>>> print(id(sample_list_c) == id(sample_list_d), id(sample_list_c), id(sample_list_d))
True 1289401453376 1289401453376
>>> #Same object
>>> 
>>> sample_list_c += ["lorem ipsum"]
>>> print(id(sample_list_c) == id(sample_list_d), id(sample_list_c), id(sample_list_d))
True 1289401453376 1289401453376
>>> #Still the same object
>>> 
>>> print(sample_list_c, sample_list_d)
['sample'] ['sample']
>>> #The contents are the same

I used to use it for debugging before, but with the advent of ptvsd, I stopped using it.

Extra edition

try-finally statement

Always run last, with or without exceptions.

>>> try:
...     sample = 0 / 0
... finally:
...     print("--- Fin ---")
--- Fin ---
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

>>> try:
...     sample = 0 / 0
... except:
...     pass
... finally:
...     print("---- Fin 2 ----")
---- Fin 2 ----

It can be used when you want to save [^ 1] regardless of whether the process could be executed. You can also use it if you don't want to cut the reference with del.

[^ 1]: Is there such a time?

for-else statement

Executes the contents of else when for completes successfully. If you break the loop with break, it will not be executed.

>>> for x in range(3):
...     print(x)
... else:
...     print("Fin !")
...
0
1
2
Fin !

>>> for x in range(3):
...     print(x)
...     break
... else:
...     print("Fin !")
0

Is it when you want to set the default value when you search and cannot find it? In that case, you should set the default value first and overwrite it with the found value ...

...... Hmm, I don't remember using it. If it's ~~, don't put it here! ~~

Tightening

If you are interested in this kind of material, I recommend Fluent Python or Effective Python. Fluent Python is 7.8 yen per page, so it's cheap when converted to pages! There are 832 pages.

In comparison, Effective Python has only 456 pages! Easy to read! Less than half of the paperback edition of Natsuhiko Kyogoku's "Moryo no Hako"! This is relatively recommended. I'm used to Python, but I want to deepen my understanding ... It's time to buy.

Recommended Posts

Useful Python built-in functions that you use occasionally
Python built-in functions ~ Zip ~
python Creating functions that you can remember later
Wrap Python built-in functions
You should know if you use Python! 10 useful libraries
Built-in python
[Python] Use pandas to extract △△ that maximizes ○○
Conquer 69 Python built-in functions 6th p ~ r
Easily use your own functions in Python
Python functions
Built-in functions
[Python] Understand how to use recursive functions
Use C ++ functions from python with pybind11
Until you can use opencv with python
Use Python and MeCab with Azure Functions
Correspondence between Python built-in functions and Rust
Two document generation tools that you definitely want to use if you write python
Until you use PhantomJS with Python on Heroku
Python built-in object
Python built-in object
[Beginner] Python functions
Python Easy-to-use functions
Python basics: functions
Python's built-in functions
String manipulation with python & pandas that I often use
Use Cursur that closes automatically with sqlite3 in Python
% And str.format () in Python. Which one do you use?
Makes you think that Python regular expressions are great
Site notes to help you use NetworkX with Python
[Python] How do you use lambda expressions? ?? [Scribbles] [Continued-1]
Not surprisingly known! ?? What about the arguments of built-in functions? What school are you from? [Python]