(Python3) No. oO (Are you using the standard library?): 5 shaders

Shade functions

Python is said to come with a battery, so it has a lot of built-in functions and standard libraries. On the other hand, I think there are many functions that are too rich to see the light of day.

The original motivation for writing this is the print function. It should be evaluated more.

Let's go on a trip!

Let's read the following once: Python Tutorial as well as Standard Library Mini Tour Standard Library Mini Tour Part 2

print The child itself is very famous, but the arguments may be shaders.

In Python2, the print statement changed from Python3 to the print function. I was wondering what it means other than breaking backward compatibility, but if you look closely, it has evolved into a very convenient function. T:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

- sep - You can set the delimiter, similar to join:

print('a', 'b', 'c', 'd', sep='_')
# '_'.join(['a', 'b', 'c', 'd'])
>>> a_b_c_d

- end - You can specify what to put at the end of the output. The default is of course \ n:

print('Hello ', end=''); print('World')
>>> Hello World

- file - This is the most moving point. ** File output is possible with print **:

f = open('output.txt', 'w')
print('Hello World', file=f)

When you google, it is often introduced how to use write () or writeline (), but from now on you can use print!

- flush - You can flush the buffer. For example, writing a file is not when you run print (..., file = f), but when the buffer is full. Probably for performance, If you want to peek at the written file during execution, you want it to be output immediately. In such a case, set flush to True.

-Matching technique- For example, suppose you want to print the number of loops to the console when doing something:

for i in range(100):
	print('rep = {0}'.format{i})
	#Something like the following...

>>> rep = 0
	rep = 1
	rep = 2
	rep = 3
	...

But this is a waste of console space with the output lined up vertically. ** Let's overwrite the output: **

for i in range(100):
	print('rep = {0}'.format{i}, '\r', end='', flush=True)
	#Something like the following...

\ r is an escape sequence that returns the cursor position to the beginning of the line. This overwrites the output and fits on one line. It's convenient.

pprint ** pretty-print, abbreviated pprint **. As the name implies, it makes the output cute. Probably the definition of "cute" here is "output that does not fit the width of the console is divided into multiple lines. It seems to be "output state":

from pprint import pprint

pprint('There should be one-- and preferably only one --obvious way to do it.'.split())

>>> ['There',
	'should',
	'be',
	'one--',
	'and',
	'preferably',
	'only',
	'one',
	'--obvious',
	'way',
	'to',
	'do',
	'it.']

I don't know if it's cute, but it can be useful. It doesn't feel as versatile as the print function.

shelve It is common to save the numerical calculation result in a txt, csv file, etc., but if you try to read this again with Python, it will be a string type, so you have to follow the procedure of casting it to int / float ... No. ** shelve can save and expand objects in Python as is: **

import shelve

zen_string = 'There should be one-- and preferably only one --obvious way to do it.'
zen_list = zen_string.split()

#Create a new Helve object
obj = shelve.open('./test')
#Substitution like dict type
obj['string'], obj['list'] = zen_string, zen_list
#Save(close)
obj.close()

#Deployment
obj_restore = shelve.open('./test')
print(list(obj_restore.keys()))
>>> ['string', 'list']

print(obj_restore['string'])
>>> 'There should be one-- and preferably only one --obvious way to do it.'

This should be useful if you live in Python! But is it versatile because it cannot be accessed from other languages and tools?

collections.deque list is a convenient container, but adding / removing elements other than the end is very inefficient. collections.deque can execute append and pop at both ends at high speed:

import numpy as np
from collections import deque
a = np.linspace(0, 1, 100000)
b = deque(a)

# IPython
%timeit -n5 a.pop(0)
>>> 5 loops, best of 3: 35.6 µs per loop

%timeit -n5 b.popleft()
>>> 5 loops, best of 3: 147 ns per loop

** 200 times or more ** </ font> is fast. If you use Python with Procon, I think it is essential.

Bonus: IPython

The convenience of IPython has been talked about in many places: How to use IPython

If you add ? After the command, you can refer to the help, you can use the shell command as it is, and it is convenient such as magic command.

IPython.embed Stop in the middle of running the code and enter IPython.

from IPython import embed

tmp = []
for i in range(100):
    tmp.append(i)
    if i == 50:
		# i ==Enter with IPython at 50
        embed()

# IPython
In [1]: tmp
Out[1]:
[0,
 1,
 2,
 ...
 50]
# exit()Or Ctrl-When I exit IPython with D or something, execution resumes

For example, if a strange error occurs, you can check the contents of the object by inserting ʻembed ()` just before that. For those who want to graduate from print debugging but the debugger has a high threshold ... I'd love to.

at the end

I've listed some of the things I use a lot that aren't very well known. If there's something good, I'll add it. If there's something good, please let me know.

Recommended Posts

(Python3) No. oO (Are you using the standard library?): 5 shaders
About the development environment you are using
Enum types that enter the standard library from Python 3.4 are still useful
Aggregate test results using the QualityForward Python library
Check the type of the variable you are using
What are you using when testing with Python?
Using the National Diet Library Search API in Python
Using the LibreOffice app in Python (1) Where are the macros?
I tried using the Python library from Ruby with PyCall
How to debug the Python standard library in Visual Studio
If you think that the person you put in with pip doesn't work → Maybe you are using python3?
When you want to use multiple versions of the same Python library (virtual environment using venv)
pathlib Are you all using it?
Tokenize using the Hugging Face library
[Python] Adjusted the color map standard
[Python] How to import the library
Extract the targz file using python
Try using the Python Cmd module
Installation method using the pip command of the Python package (library) Mac environment
If you are told cannot by Python import, review the file name
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Behind the flyer: Using Docker with Python
Working with OpenStack using the Python SDK
Let's summarize the Python coding standard PEP8 (1)
What is "mahjong" in the Python library? ??
Reboot the router using Python, Selenium, PhantomJS
Python standard library: second half (Python learning memo ⑨)
From Python 3.4, pip becomes the standard installer! ??
python setup.py test the code using multiprocess
Python standard library: First half (Python learning memo ⑧)
Python open and io.open are the same
Get the size of the image file on the web (Python3, no additional library required)
How to get the notebook name you are currently using in Google Colab
I tried using the Python library "pykakasi" that can convert kanji to romaji.
Feel free to turn Python using the library into an AWS Lambda function
There are times when you can shorten the if statement using max · min