Pythonic Flashcards
1
Q
Add boolean check to a class
A
class AClass: def \_\_init\_\_(self): self.data = [] def \_\_bool\_\_(self): return True if self.data else False
2
Q
Choose a random character from a string
A
item = random.choice(string)
3
Q
Fastest check if something is ‘in’ for loop
A
for _ in range(0, 1000000): b = m in {Moves.North, Moves.South, Moves.West, Moves.East} # slowest b = m == Moves.North or m == Moves.South or m == Moves.West or m == Moves.East # slow b = m in {Moves.North, Moves.South, Moves.West, Moves.East} # fastest
4
Q
Exit codes
A
import sys sys.exit(0) # success sys.exit(1) # failure
5
Q
Force the output buffer
A
import sys for i in range(5): print(i, end=' ') sys.stdout.flush() # Forces the buffer to flush time.sleep(1)
6
Q
How to prevent nesting?
A
Use guard clauses to invert ‘if’
~~~
if not data:
return “No data provided”
~~~