After years of using Python, I stumbled upon features and features that we didn't know in the past. Some can be said to be very useful, but they are not fully utilized. With that in mind, I've edited some of the features of Python that you should know about.
Functions with any number of parameters
You may already know that Python allows you to define optional parameters. But there is also a way to define any number of arguments to the function.
First, look at the following is an example that defines only optional parameters
The 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 arbitrary arguments. We use tuples to achieve
The code is as follows:
def foo (*args): # Just use ' * ' to collect-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
Find files using Glob ()
Most python functions have long, descriptive names. But a function named Glob () you probably don't know what it's doing unless you're familiar with it from somewhere else.
It is like a more powerful version of the Listdir () function. It allows you to search for files by using pattern matching.
The 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 find multiple file types as follows:
The 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 many filetype arguements
Print filename
# output
#=========#
# Test.txt
# arg.py
# g.py
# shut.py
# test.py
If you want to get the absolute path to each file, you can call the Realpath () function on the return value:
The 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 many 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 useful for debugging purposes and is much more powerful than what is described here.
This article will not cover every detail of this module, but will show you some use cases.
The code is as follows:
Import logging, inspect
Logging.basicconfig (Level=logging.info,
format= '% (asctime) s% (levelname) -8s% (filename) s:% (lineno) -4d:% (message) s ',
datefmt= '%m-%d%h:%m ',
)
Logging.debug (' A debug Message ')
Logging.info (' Some information ')
Logging.warning (' A shot across 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 ()
# should print the following (with current date/time of course)
#10 -19 19:57 INFO test.py:9: Some Information
#10 -19 19:57 WARNING test.py:10:a shot across the bow
# (, ' c:/xxx/pyfunc/magic.py ', +, ', [' Test () \ n '], 0)
Generate a unique ID
In some cases you need to generate a unique string. I've seen a lot of people use the MD5 () function to do this, but it's really not for this purpose. In fact, there is a Python function named UUID () for this purpose.
The 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 might notice that even though the strings are unique, the few characters behind them look similar. This is because the generated string is associated with the MAC address of the computer.
To reduce the duplication, 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 of
Have you ever needed to store a complex variable in a database or text file? You don't have to think of a fancy way to convert an array or an object into a typed string, because Python already provides this functionality.
The code is as follows:
Import Pickle
variable = [' Hello ', [1, '] ', ' 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 ' both '
# p3
# AaS ' Apple '
# P4
# A.
# [' Hello ', [1, ' + '], ' Apple ']
This is a native Python serialization method. In recent years, however, JSON has become popular, and Python has added support for it. Now you can use JSON to encode and decode.
The code is as follows:
Import JSON
variable = [' Hello ', [1, '] ', ' 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 ', [1, ' + '], ' apple ']-
# encoded ["Hello", "1", "Double"], "apple"]-
# decoded [u ' Hello ', [1, U ', '], U ' Apple ']-
This is more compact and, most importantly, compatible with JavaScript and many other languages. However, for complex objects, some of the information may be lost.
Compressed characters
When we talk about compression, we usually think of files, such as the ZIP structure. Long characters can be compressed in Python, and no files are involved.
The 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 pretium orci,
Non ultricies elit lacus quis ante. Lorem ipsum dolor
Sit amet, consectetur adipiscing elit. Aliquam
Pretium ullamcorper 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
Registering the Shutdown function
There are modules called atexit, which allow you to execute some code immediately after the script has finished running.
If you want to measure some benchmark data at the end of the script execution, such as how long it takes to run:
The 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):
# File "C:\Python27\lib\atexit.py", line +, in _run_exitfuncs
# func (*targs, **kargs)
# TypeError: ' str ' object is not callable
# Error in Sys.exitfunc:
# Traceback (most recent):
# File "C:\Python27\lib\atexit.py", line +, in _run_exitfuncs
# func (*targs, **kargs)
# TypeError: ' str ' object is not callable
Drilling looks very simple. Just add the code to the bottom of the script and it will run before the end of the script. 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 executes regardless of the reason the script stops running.
Conclusion
Are you aware that the Python features are not widely known to be useful? Please share it with us at the comment office. Thank you for reading!