- Use type hinting wherever possible to introduce strong typing and remove possibilities of the code being used incorrectly
Type hinting in Python is similar to mentioning the argument and return types in statically-typed languages like C++. The difference is, type hinting is optional in Python. The worst that happens when you write the wrong type hints is that you get warnings from linter and type checker programs like mypy
- Use dataclasses for strongly typed interfacing and to show what the function is actually returning (both types and nature of content)
- You can use
typing.Union()
ordataclass1 | dataclass2 | ...
to unionize different types to enable efficient pattern matching - Enclose an integer literal in
()
when using methods directly on it, in order to avoid aSyntaxError
. This is because Python will interpret42.as_integer_ratio()
as a decimal given the point, resulting in an error. The right way to do this is(42).as_integer_ratio()
num.hex()
will convertnum
to hex. To convert a hexadecimal to a float, usefromhex()
- To center a string by padding it with a specified character, use
center(width[, fillchar])
.Width
is the final length of the string andfillchar
is the character you want to pad the string with itertools.groupby()
groups adjacent elements together