Operators
|
Modulo |
|
Power |
|
Addition, string concat, list concat |
|
|
|
|
|
Floor division |
|
Logical operators |
|
Identity operators |
|
Membership operators |
|
Bitwise operators |
|
Ternary operator |
Useful Packages
dacite |
This module simplifies creation of data classes (PEP 557) from dictionaries. |
requests |
Requests is a simple, yet elegant, HTTP library. |
Main
def main():
print("Hello World")
if __name__ == '__main__':
main()
|
main() is only called when file is ran directly.
If the file is imported into another module, main()
is not called.
Closures
from typing import Callable
def outer_func(message: str) -> Callable[[], None]:
def inner_func() -> None:
print(message)
return inner_func
# Calling
do_print = outer_func("Hello world")
print("Now we actually print ...")
do_print()
|
While the function outer_function()
completed, the message
was rather preserved but hidden and attached to the code.
Decorators make heavy use of this.
Exception Handling
try: pass except Exception as e: pass finally: pass
|
e.add_note("Some info")
|
Add some extra context info to exception |
|
Reraise the exception |
|
Chained exception; indicate that NewError was caused by e |
Nested Functions
def outer_func(message: str) -> None:
def inner_func() -> None:
print(message)
inner_func()
|
Nested functions can access variables of enclosing scopes, but they are readonly. Can be circumvented using nonlocal
keyword.
Loops
|
|
|
Loop control |
|
Alternative if loop condition false from beginning |
Classes
class Dude:
def __init__(self, name: str) -> None:
self.name = name
def introduce(self) -> str:
return f"Hello, I am {self.name}"
my_object = Dude("ThaDude")
print(my_object.introduce())
|
Leftovers
|
These are all consider False
in a logical expression |
|
|
Input / Output
print("Hello, %s" % name)
|
C++ like printf() |
print(f"Hello, {name}")
|
In-place expressions |
|
Read till newline |
|
Expects exactly 1 int |
a, b = map(int, input().split())
|
Expects exactly 2 ints |
array = input().split()
|
JSON
|
json_obj = json.loads(json_string)
|
Convert string to data object |
json_string = json.dumps(json_obj)
|
Convert data object to string |
Python supports a similar data serialization method called pickle
which can be used in exactly the same way.
Code Introspection
|
Show help on class, function, method, ... |
|
Return all the properties and methods, even built-in properties which are default for all object. |
|
Returns True if the specified object has the specified attribute |
|
Returns a unique id for the specified object. |
|
Returns the type of the specified object |
|
Returns the canonical string representation of the object. |
|
Return whether the object is callable (i.e., some kind of function). |
|
Return whether 'cls' is derived from another class or is the same class. |
|
Return whether an object is an instance of a class or of a subclass thereof. |
Remember that in python everything is an object.
Dictionaries
|
Initialize |
|
Assign element |
for key,value in book.items():
|
|
No return value |
|
Returns value |
|
Key / Value storage. Key can also be anything
Packages
|
__all__ = [ "public_module" ]
|
Override exports and keep certain modules internal |
A directory that get's its own namespace containing modules and other packages.
Regular Expressions
|
pattern = re.compile(r"...")
|
Todo: add search, replace, matching, ...
Generators
import random
from typing import Generator
def lottery() -> Generator[int, None, None]:
for i in range(6):
yield random.randint(1, 43)
yield random.randint(1, 20) # Joker
# Usage:
for number in lottery():
print(number)
|
Functions that returns an iterable set of items one at a time (yield).
Debugging
|
Execute the current line, stop at the first possible occasion |
|
Continue execution, only stop when a breakpoint is encountered. |
|
Print help |
|
Print something like a variable |
Just add breakpoint()
somewhere in code and when execution comes to this point you will be dropped to pdb, an interactive source code debugger.
Decorators
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function call")
func(*args, **kwargs)
print("After the function call")
return wrapper
@simple_decorator
def greet(name: str):
print(f"Hello there {name}!")
greet("King")
# @decorator replaces this:
decorate = simple_decorator(greet)
decorate("King")
|
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are typically applied to functions, and they play a crucial role in enhancing or modifying the behavior of functions.
When you create a decorator, the wrapper function (inside the decorator) is a closure. It retains access to the function being decorated and any additional state or arguments defined in the decorator function.
|