Some useful functions and functions in Python are shared. python is very useful.
After using Python for many years, I accidentally discovered some features that we did not know in the past. Some of them can be said to be very useful, but they are not fully utilized. With this in mind, I have edited some Python features you should know.
Functions with any number of parameters
You may already know that Python allows you to define optional parameters. However, there is another way to define any number of parameters of a function.
First, let's see an example of defining only optional parameters.
Copy codeThe Code is as follows:
Def function (arg1 = "", arg2 = ""):
Print "arg1: {0}". format (arg1)
Print "arg2: {0}". format (arg2)
Function ("Hello", "World ")
# Prints args1: Hello
# Prints args2: World
Function ()
# Prints args1:
# Prints args2:
Now let's see how to define a function that can accept any parameter. We use tuples to implement
Copy codeThe Code is as follows:
Def foo (* args): # just use "*" to collect all remaining arguments into a tuple
Numargs = len (args)
Print "Number of arguments: {0}". format (numargs)
For I, x in enumerate (args ):
Print "Argument {0} is: {1}". format (I, x)
Foo ()
# Number of arguments: 0
Foo ("hello ")
# Number of arguments: 1
# Argument 0 is: hello
Foo ("hello", "World", "Again ")
# Number of arguments: 3
# Argument 0 is: hello
# Argument 1 is: World
# Argument 2 is: Again
Use Glob () to find files
Most Python functions have long and descriptive names. But you may not know what a function named glob () is doing unless you are familiar with it elsewhere.
It is like a more powerful version of The listdir () function. It allows you to search for files by using pattern matching.
Copy codeThe Code is as follows:
Import glob
# Get all py files
Files = glob. glob ('*. py ')
Print files
# Output
# ['Arg. py', 'G. py', 'shut. py', 'test. py']
You can search for multiple file types as follows:
Copy codeThe Code is as follows:
Import itertools as it, glob
Def multiple_file_types (* patterns ):
Return it. chain. from_iterable (glob. glob (pattern) for pattern in patterns)
For filename in multiple_file_types ("*. txt", "*. py"): # add as your filetype arguements
Print filename
# Output
#======== #
# Test.txt
# Arg. py
# G. py
# Shut. py
# Test. py
If you want to obtain the absolute path of each file, you can call the realpath () function in the return value:
Copy codeThe Code is as follows:
Import itertools as it, glob, OS
Def multiple_file_types (* patterns ):
Return it. chain. from_iterable (glob. glob (pattern) for pattern in patterns)
For filename in multiple_file_types ("*. txt", "*. py"): # add as your filetype arguements
Realpath = OS. path. realpath (filename)
Print realpath
# Output
#======== #
# C: \ xxx \ pyfunc \ test.txt
# C: \ xxx \ pyfunc \ arg. py
# C: \ xxx \ pyfunc \ g. py
# C: \ xxx \ pyfunc \ shut. py
# C: \ xxx \ pyfunc \ test. py
Debugging
The following example uses the inspect module. This module is very useful for debugging purposes and has far more functions than described here.
This article will not cover every detail of this module, but will show you some examples.
Copy codeThe Code is as follows:
Import logging, inspect
Logging. basicConfig (level = logging. INFO,
Format = '% (asctime) s % (levelname)-8 s % (filename) s: % (lineno)-4d: % (message) s ',
Datefmt = '% m-% d % H: % m ',
)
Logging. debug ('a debug message ')
Logging.info ('some information ')
Logging. warning ('a shot every SS the bow ')
Def test ():
Frame, filename, line_number, function_name, lines, index = \
Inspect. getouterframes (inspect. currentframe () [1]
Print (frame, filename, line_number, function_name, lines, index)
Test ()
# Shocould print the following (with current date/time of course)
#10-19 19:57 INFO test. py: 9: Some information
#10-19 WARNING test. py: 10: A shot capture ss the bow
# (, 'C:/xxx/pyfunc/magic. py', 16, '', ['test () \ n'], 0)
Generate unique ID
In some cases, you need to generate a unique string. I have seen many people use the md5 () function for this purpose, but it does not. In fact, a Python function named uuid () is used for this purpose.
Copy codeThe Code is as follows:
Import uuid
Result = uuid. uuid1 ()
Print result
# Output => various attempts
# 9e177ec0-65b6-11e3-b2d0-e4d53dfcf61b
# Be57b880-65b6-11e3-a04d-e4d53dfcf61b
# C3b2b90f-65b6-11e3-8c86-e4d53dfcf61b
You may notice that even if strings are unique, the several characters behind them look very similar. This is because the generated string is related to the MAC address of the computer.
To reduce the number of duplicates, you can use these two functions.
Import hmac, hashlib
Key = '1'
Data = 'A'
Print hmac. new (key, data, hashlib. sha256). hexdigest ()
M = hashlib. sha1 ()
M. update ("The quick brown fox jumps over the lazy dog ")
Print m. hexdigest ()
# C6e693d0b35805080632bc2469e1154a8d1072a86557778c27a01329630f8917
#2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
Serialization
Do you need to store a complex variable in a database or text file? You don't need to think of a fancy way to convert arrays or object cells into formatted strings, because Python already provides this function.
Copy codeThe Code is as follows:
Import pickle
Variable = ['hello', 42, [1, 'two'], 'apple']
# Serialize content
File = open('serial.txt ', 'w ')
Serialized_obj = pickle. dumps (variable)
File. write (serialized_obj)
File. close ()
# Unserialize to produce original content
Target = open('serial.txt ', 'R ')
MyObj = pickle. load (target)
Print serialized_obj
Print myObj
# Output
#(Lp0
# S 'hello'
# P1
# AI42
# A (lp2
# I1
# AS 'two'
# P3
# AaS 'apple'
# P4
#.
# ['Hello', 42, [1, 'two'], 'apple']
This is a native Python serialization method. However, JSON has become popular in recent years, and Python has added support for it. Now you can use JSON for codec.
Copy codeThe Code is as follows:
Import json
Variable = ['hello', 42, [1, 'two'], 'apple']
Print "Original {0}-{1}". format (variable, type (variable ))
# Encoding
Encode = json. dumps (variable)
Print "Encoded {0}-{1}". format (encode, type (encode ))
# Deccoding
Decoded = json. loads (encode)
Print "Decoded {0}-{1}". format (decoded, type (decoded ))
# Output
# Original ['hello', 42, [1, 'two'], 'apple']-<type 'LIST' = "">
# Encoded ["hello", 42, [1, "two"], "apple"]-<type 'str' = "">
# Decoded [u 'hello', 42, [1, u 'two'], u 'apple']-<type 'LIST' = "">
This is more compact and most importantly compatible with JavaScript and many other languages. However, some information of complex objects may be lost.
Compressed characters
When talking about compression, we usually think of files, such as ZIP structures. In Python, long characters can be compressed without any file.
Copy codeThe Code is as follows:
Import zlib
String = "" Lorem ipsum dolor sit amet, consectetu
Adipiscing elit. Nunc ut elit id mi ultricies
Adipiscing. Nulla facilisi. Praesent pulvinar,
Sapien vel feugiat vestibulum, nulla dui presponorci,
Non ultricies elit lacus quis ante. Lorem ipsum dolor
Sit amet, consectetur adipiscing elit. Aliquam
Prepolicullamcorper urna quis iaculis. Etiam ac massa
Sed turpis tempor luctus. Curabitur sed nibh eu elit
Mollis congue. Praesent ipsum diam, consectetur vitae
Ornare a, aliquam a nunc. In id magna pellentesque
Tellus posuere adipiscing. Sed non mi metus, at lacinia
Augue. Sed magna nisi, ornare in mollis in, mollis
Sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
Eu non enim. Ut malesuada lacus eu nulla bibendum
Id euismod urna sodales ."""
Print "Original Size: {0}". format (len (string ))
Compressed = zlib. compress (string)
Print "Compressed Size: {0}". format (len (compressed ))
Decompressed = zlib. decompress (compressed)
Print "Decompressed Size: {0}". format (len (decompressed ))
# Output
# Original Size: 1022
# Compressed Size: 423
# Decompressed Size: 1022
Register the Shutdown Function
The module atexit allows you to execute some code immediately after the script is run.
If you want to measure some benchmark data at the end of script execution, such as how long it takes to run:
Copy codeThe Code is as follows:
Import atexit
Import time
Import math
Def microtime (get_as_float = False ):
If get_as_float:
Return time. time ()
Else:
Return '% f % d' % math. modf (time. time ())
Start_time = microtime (False)
Atexit. register (start_time)
Def shutdown ():
Global start_time
Print "Execution took: {0} seconds". format (start_time)
Atexit. register (shutdown)
# Execution took: 0.297000 1387135607 seconds
# Error in atexit. _ run_exitfuncs:
# Traceback (most recent call last ):
# File "C: \ Python27 \ lib \ atexit. py", line 24, in _ run_exitfuncs
# Func (* targs, ** kargs)
# TypeError: 'str' object is not callable
# Error in sys. exitfunc:
# Traceback (most recent call last ):
# File "C: \ Python27 \ lib \ atexit. py", line 24, in _ run_exitfuncs
# Func (* targs, ** kargs)
# TypeError: 'str' object is not callable
It seems very easy to blind. You only need to add the code to the bottom layer of the script, which will run before the script ends. However, if there is a fatal error in the script or the script is terminated by the user, it may not run.
When you use atexit. register (), your code will be executed, No matter why the script stops running.
Conclusion
Are you aware of the usefulness of Python features that are not widely known? Please share with us in the comments. Thank you for reading!