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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Choose a random character from a string

A
item = random.choice(string)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Exit codes

A
import sys

sys.exit(0)  # success
sys.exit(1)  # failure
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to prevent nesting?

A

Use guard clauses to invert ‘if’
~~~
if not data:
return “No data provided”
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly