closures
https://www.programiz.com/python-programming/closure
def standalone(): return "foo" if foo else "bar" standalone() # 'foo' foo=False standalone() # 'bar' # closure! def outside(foo=False): def inside(): return "foo" if foo else "bar" return inside in1 = outside() in1() # 'bar' in2 = outside(foo=True) in2() # 'foo' foo=True in1() # 'bar' in2() # 'foo' # doesn't work! outside.foo = False in2() # 'foo' in1() # 'bar' # but this does! in1.__closure__ # (<cell at 0x7fc69803ffd0: bool object at 0x1075ea618>,) in1.__closure__[0].cell_contents # False in2.__closure__[0].cell_contents # True in2.__closure__[0].cell_contents = False in2() # 'bar'
unit tests
Method | Checks that | New in |
---|---|---|
assertEqual(a, b) | a == b | |
assertNotEqual(a, b) | a != b | |
assertTrue(x) | bool(x) is True | |
assertFalse(x) | bool(x) is False | |
assertIs(a, b) | a is b | 3.1 |
assertIsNot(a, b) | a is not b | 3.1 |
assertIsNone(x) | x is None | 3.1 |
assertIsNotNone(x) | x is not None | 3.1 |
assertIn(a, b) | a in b | 3.1 |
assertNotIn(a, b) | a not in b | 3.1 |
assertIsInstance(a, b) | isinstance(a, b) | 3.2 |
assertNotIsInstance(a, b) | not isinstance(a, b) | 3.2 |
enum
Auto names in Enums docs.python.org.
from enum import Enum, auto class Color(Enum): RED = auto() BLUE = auto() GREEN = auto() list(Color) # returns: # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Add a AutoName
class,
class AutoName(Enum): def _generate_next_value_(name, start, count, last_values): return name class Ordinal(AutoName): NORTH = auto() SOUTH = auto() list(Ordinal) # returns: # <Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>]