Misc¶
https://docs.python-guide.org/writing/gotchas/
https://stackoverflow.com/questions/101268/hidden-features-of-python
- The
inttype in Python 3 is unbounded, which means that there is no limit on the range of integer numbers that anintcan represent. However, there are still various integer related limits in Python 3 due to the interpreter's word size (sys.maxsize) (which is the same as the machine's word size in most cases). This number is the size of the largest possible list or in-memory sequence.
x = 1111111111111111111111111111111111111111111111111111111111111111111111111111
type(x)
- Use type annotation to make your code more readable and easier to understand.
Functions and Classes¶
Restrict the types of objects that your function/method can be applied to and throw a (ValueError) exception when a wrong type is provided. This helps minimize surprisings. If you must make a function accepts 2 (or more) customized types of objects, it is best to make them have similar duck types. For example, one object has members
mem1andmem2(which are used in the function), instead of representing the 2nd type of object as a tuple (of 2 elements) it is better to define a class to match interfaces of the first type of object so that implementation of the function is simple and concise. Noticce that dataclass is a good way to implement simple classes.AVOID returning objects of different types from a Python function/method.
Almost all modern programming languages follow the convention of not returnting anything (or in another words, retun void, None, etc.) from a mutator method so that you cannot chain on a mutator method. Functional programming languages enough chaining on methods as they often have immutable objects and the methods return new objects rather than changing the original objects.
Python functions (except lambda functions) do not automatically return value unlike functional programming languages. Forgotting a
returnstatement is a common mistake in Python.
- You cannot use
returnto return result from a generator function. Instead areturnbehaves like raising a StopIteration. Please see this issue for more discussions.
https://jeffknupp.com/blog/2018/10/11/write-better-python-functions/
https://stackoverflow.com/questions/1839289/why-should-functions-always-return-the-same-type
Operator Precedence¶
- According to Python Operator Precedence,
the ternary expression
if - elsehas a very low precedence. However, it has higher precedence than the tuple operator,. It is suggested that you always use parentheses to make the precedence clear when you use the ternary expression in a complicated expression. Below is an example illustrating the precedence of the ternary expression.
update = {
"status": "succeed",
"partitions": 52,
"size": 28836,
"end_time": 1563259850.937318,
}
[
key + " = " + f"{val}" if isinstance(val, (int, float)) else f"'{val}'"
for key, val in update.items()
]
update = {
"status": "succeed",
"partitions": 52,
"size": 28836,
"end_time": 1563259850.937318,
}
[
key + " = " + (f"{val}" if isinstance(val, (int, float)) else f"'{val}'")
for key, val in update.items()
]

Python Doc¶
https://docs.quantifiedcode.com/python-anti-patterns/index.html
Comprehensive Python Cheatsheet
Environment Variable¶
Please refer to Dealing With Environment Variables in Python for detailed discussions.
Programming Skills¶
Python varadic args can mimic function overloading
Python eval
*argsand**kwargs. Arguments after*must be called by name.sys.stdout.write,sys.stdout.flush,printGlobal variables in a Python module are readable but not writable to functions in the same module by default. If you want to write to a global variable in a function (in the same module), you have to declare the global variable in the method using the keyword
global. For example, ifxis a global variable and you want to write to it in a method, you have to declareglobal xat the beginning of the method.
Numerical¶
- Division is float division in Python 3 which is different from Python 2.
If you want integer division,
use the
//operator.
Misc¶
Keys for set and dict objects must be immutable in Python (and the same concept holds in other programming languages too). Since a list in Python is mutable, it cannot be used as a key in set and dict objects. You have to convert it to an immutable equivalence (e.g., tuple).
Use sys.exit(msg) to print error message and quit when error happens
Get the class name of an object.
type(obj).__name__
File System¶
os.mkdiracts likemkdirin Linux andos.makedirsacts likemkdir -pin Linux. Both of them throw an exception if the file already exists.Use
execfile(open(filename).read())to source a file, variables defined in 'filename' are visible, however, imported packages are invisible to the script running execfile
Encoding¶
ord unichar
return ascii number of characters
chr return a string from a ascii number
Syntax¶
Python expression is calculated from left to right.
You can use a
dictstructure to mimic switch in other programming languages. However, it is kind of evil and has very limited usage., You should avoid use this. Just use multipleif ... else ...branches instead.:has higher priority than arithmetic operators in Python, which is opposite to that in R.return v1, v2returns a tuple(v1, v2). And if a functionfreturns a tuple(v1, v2, v3), you can usev1, v2, v3 = f()Stay away from functions/methods/members starting with
_. For example, you should use the built-in functionlento get the length of a list instead of using its method__len__.Python does not support
++,--but support+=,-+, etc.