< Python > Some python tricks you may never use But you should know
namedtuple
If you are too lazy to create a class but you still want to use a variable that can act as a class object, then you should use namedtuple:
1 | from collections import namedtuple |
result:
1 | (1,2,3) |
decorator
If you are too lazy to change a function from inner code but you still want to add some new features to a function, you should use decorator. For example, if you want to print “hello” when you add two numbers:
1 | def hello(fn): |
result:
1 | hello |
or you can use operator “@” to implement your function elegantly:
1 | def hello(fn): |
enumerate
If you are too lazy to count the index of a list in a loop but you still need the index, then you should use enumerate:
1 | a = ['a', 'b', 'c'] |
result:
1 | (0, 'a') |
iterator
If you are too lazy to get the every elements in a list by index but you still want to get every element in order, then you should use iterator:
1 | def inc(): |
result:
1 | 0 |
Do not easily copy object in python
If you are too lazy to get deepcopy a other object but you still want get a copy of a exists one, then you many creating a bug in you code!
In python, all things are objects, even class is a kind of object. If you want to copy a object, then the ID of these two objects are the same which means the two objects are are stored in the same place. If you modify one object, then another object are also modified.
1 | class sample: |
result:
1 | (['1', 'a', 'b'], ['1', 'a', 'b']) |
another example:
1 | a = [1,2,3,4] |
result:
1 | [100,2,3,4] |
Instead, you should use “deepcopy” to copy two objects
1 | a = [1,2,3,4] |
result:
1 | [1,2,3,4] |
itertools
If you are too lazy to write a infinite loop in an iterator but you still want to reset to loop when iteration finished, then you should use itertools:
1 | import itertools |
result:
1 | 1 |
concurrent.futures
If you are too lazy to write a multi-thread to process all the elements in a list which may cost lots of time, then you should use a python build-in multi-thread tools:
1 | import concurrent.futures |
result:
1 | 0 |
< Python > Some python tricks you may never use But you should know