10 Development Tips For Python [Part-1]
Updated: Dec 31, 2020
How to view the source code in the running state?
We usually use IDE to view the source code of the function.
For example, in PyCharm, you can Ctrl + mouse click to enter the source code of the function.
What if there is no IDE?
When we want to use a function, how do we know which parameters the function needs to receive?
When we have problems when using functions, how to troubleshoot the problem by reading the source code?

HashTags: #python #PythonProgramming #Coding #Programming #PythonDevelopment #pythonLoop#pythonLearning#pythonTutorial#pythonIFElse#pythonProgramming#pythonFunction#pythonCode#pythonWhileLoop#pythonMap#pythonString#pythonArray#pythonListComprehension#pythonOnlineCompiler#pythonJson#pythonCompiler
At this time, we can use Inspect instead of IDE to help you accomplish these things:
# demo.py
import inspect
def add(x, y):
Return x + y
print("===================")
print(inspect.getsource(add))
The results are as follows:
$ python demo.py
===================
def add(x, y):
return x + y
How to turn off automatic context correlation for exceptions?
When you are handling an exception and another exception is thrown due to improper handling or other problems, the exception thrown out will also carry the original exception information.
It's like this:
try:
print(1 / 0)
except Exception as exc:
raise RuntimeError("Something bad happened")
We can see two exception messages from the output:
Traceback (most recent call last):
File "demo.py", line 2, in <module>
print(1 / 0)
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "demo.py", line 4, in <module>
raise RuntimeError("Something bad happened")
RuntimeError: Something bad happened
If an exception is raised in an exception handler or finally block, by default, the exception mechanism will work implicitly and attach the previous exception to the "__context__" attribute of the new exception. This is the automatic correlation exception context that Python turns on by default.
If you want to control this context yourself, you can add a from the keyword (the from syntax has a limitation, that is, the second expression must be another exception class or instance), to indicate which exception is directly causing your new exception.
try:
print(1 / 0)
except Exception as exc:
raise RuntimeError("Something bad happened") from exc
The output is as follows:
Traceback (most recent call last):
File "demo.py", line 2, in <module>
print(1 / 0)
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "demo.py", line 4, in <module>
raise RuntimeError("Something bad happened") from exc
RuntimeError: Something bad happened
Of course, you can also use the "with_traceback()" method to set the context "__context__ "attribute for the exception, which can also better display the exception information in the traceback.
try:
print(1 / 0)
except Exception as exc:
raise RuntimeError("bad thing").with_traceback(exc)
Finally, what if I want to completely turn off this mechanism for automatically correlating exception contexts? what else can we do?
You can use "raise...from None", from the following example, there is no original exception:
$ cat demo.py
try:
print(1 / 0)
except Exception as exc:
raise RuntimeError("Something bad happened") from None
$
$ python demo.py
Traceback (most recent call last):
File "demo.py", line 4, in <module>
raise RuntimeError("Something bad happened") from None
RuntimeError: Something bad happened
(PythonCodingTime)
The fastest way to view the package search path
When you use "import" to import a package or module, Python will search in some directories, and these directories have a priority order, and normal people will use "sys.path" to view it.
>>> import sys
>>> from pprint import pprint
>>> pprint(sys.path)
['',
'/usr/local/Python3.7/lib/python37.zip',
'/usr/local/Python3.7/lib/python3.7',
'/usr/local/Python3.7/lib/python3.7/lib-dynload',
'/home/wangbm/.local/lib/python3.7/site-packages',
'/usr/local/Python3.7/lib/python3.7/site-packages']
>>>
Is there a faster way?
Is there a way I don’t even need to enter the console mode?
You might think of this, but it is essentially the same as the above.
[wangbm@localhost ~]$ python -c "print('\n'.join(__import__('sys').path))"
/usr/lib/python2.7/site-packages/pip-18.1-py2.7.egg
/usr/lib/python2.7/site-packages/redis-3.0.1-py2.7.egg
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/home/wangbm/.local/lib/python2.7/site-packages
/usr/lib64/python2.7/site-packages
/usr/lib64/python2.7/site-packages/gtk-2.0
/usr/lib/python2.7/site-packages
What I want to introduce here is more convenient than the above two methods, one line of command can be solved.
[wangbm@localhost ~]$ python3 -m site
sys.path = [
'/home/wangbm',
'/usr/local/Python3.7/lib/python37.zip',
'/usr/local/Python3.7/lib/python3.7',
'/usr/local/Python3.7/lib/python3.7/lib-dynload',
'/home/wangbm/.local/lib/python3.7/site-packages',
'/usr/local/Python3.7/lib/python3.7/site-packages',
]
USER_BASE: '/home/wangbm/.local' (exists)
USER_SITE: '/home/wangbm/.local/lib/python3.7/site-packages' (exists)
ENABLE_USER_SITE: True
From the output, you can find that the path in this column is more comprehensive than "sys.path", and it contains the directory of the user environment.
Write the nested for loop as a single line
We often use the following nested for loop code:
list1 = range(1,3)
list2 = range(4,6)
list3 = range(7,9)
for item1 in list1:
for item2 in list2:
for item3 in list3:
print(item1+item2+item3)
Here are just three for loops, in actual coding, there may be more.
The readability of such code is very poor, many people don't want to write it, but there is no better way to write it.
Here is a way of writing that I often use, using the IterTools library to implement more elegant and readable code.
from itertools import product
list1 = range(1,3)
list2 = range(4,6)
list3 = range(7,9)
for item1,item2,item3 in product(list1, list2, list3):
print(item1+item2+item3)
The output is as follows:
$ python demo.py
12
13
13
14
13
14
14
15
How to use Print to output log
Beginners like to use "print" to debug the code and record the running process of the program.
But "print" will only output the content to the terminal and cannot be persisted in the log file, which is not conducive to troubleshooting.
If you are keen to use "print" to debug code (although this is not the best practice) and record the running process of the program, then the usage of "print" described below may be useful to you.
As a function, "print" in Python 3 has become more powerful because it can receive more parameters. When you specify some parameters, you can output the content of print to the log file
The code is as follows:
>>> with open('test.log', mode='w') as f:
... print('hello, python', file=f, flush=True)
>>> exit()
$ cat test.log
hello, python