After years of using Python, I stumbled across features and features that we didn't know about before. Some can be said to be very useful, but not fully utilized. With that in mind, I edited some of the python features you should know about.
Functions with any number of arguments
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 a function.
First, let's look at an example that defines only optional parameters.
Copy Code code 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 look at how to define a function that takes any parameter. We use tuples to implement
Copy Code code 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, descriptive names. But a function named Glob () you may not know what it is, unless you are familiar with it elsewhere.
It's like a more powerful version of the Listdir () function. It allows you to search for files by using pattern matching.
Copy Code code 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:
Copy Code code as follows:
Import Itertools as it, Glob
def multiple_file_types (*patterns):
Return it.chain.from_iterable (Glob.glob (pattern) to 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 of each file, you can call the Realpath () function on the return value:
Copy Code code as follows:
Import Itertools as it, Glob, OS
def multiple_file_types (*patterns):
Return it.chain.from_iterable (Glob.glob (pattern) to 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 far more functional than described here.
This article will not cover every detail of this module, but will show you some use cases.
Copy Code code 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 called UUID () that is used for this purpose.
Copy Code code 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 though the strings are unique, a few of the characters behind them look very similar. This is because the generated string is associated with the computer's MAC address.
To reduce the repetition, 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
Do you ever need 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 object to a typed string, because Python already provides this functionality.
Copy Code code as follows:
Import Pickle
variable = [' Hello ', +, [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
# A.
# [' Hello ', 1, ' two '], ' 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 codec.
Copy Code code as follows:
Import JSON
variable = [' Hello ', +, [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 ', 1, ' two '], ' apple '-<type ' list ' = ' >
# encoded ["Hello", "1", "two"], "apple"]-<type ' str ' = ' >
# decoded [u ' Hello ', 1, U ' two '], U ' apple '-<type ' list ' = ' >
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 zip structures. In Python, you can compress long characters without involving any file files.
Copy Code code 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,
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, 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 is a module called Atexit, which allows you to execute some code immediately after the script has run out.
If you want to measure some baseline data at the end of the script execution, such as how long it took to run:
Copy Code code 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, 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, in _run_exitfuncs
# func (*targs, **kargs)
# typeerror: ' str ' object is not callable
Drilling seems very simple. Just add code to the bottom of the script and it 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 execute regardless of why the script stops running.
Conclusion
Are you aware that the Python features are not widely known to be useful? Please share it with us in the comments office. Thank you for reading!