Skip to content

Instantly share code, notes, and snippets.

View async_function_not_used.py
>>> import time
>>> def login_user():
... time.sleep(2)
...
>>> def load_posts():
... time.sleep(3)
...
>>> def launch_app():
... print("Open App:", time.asctime())
... login_user()
View function_partial.py
>>> from functools import partial
>>> def incrementer(start, step):
... return start + step
...
>>> incrementer_by_one = partial(incrementer, step=1)
>>> incrementer_by_one(5)
6
View function_repr.py
>>> class Student:
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return f"Student({self.name!r})"
...
>>> student = Student("John")
>>> student
Student('John')
View class_property.py
>>> class Product:
... def __init__(self, name, price):
... self.name = name
... self.price = price
...
... @property
... def employee_price(self):
... return self.price * 0.9
...
>>> vacuum = Product("Vacuum", 200)
View class_methods.py
class Student:
def __init__(self, name):
self.name = name
def study(self):
print(f"The student {self.name} is studying.")
@staticmethod
def is_adult(age):
return age >= 18
View function_docstring.py
def calculate_fraction(a, b):
"""
Calculate a fraction of two numbers
:param a: int or float, the numerator of the fraction
:param b: int or float, the denominator of the fraction
:return: float, calculated as a /b
:raise: ZeroDivisionError (when b is zero)
"""
return a / b
View decorator_example.py
def logging_time(func):
def logger(*args, **kwargs):
start = time.time()
returned = func(*args, **kwargs)
end = time.time()
print(f"Calling {func.__name__} time: {end - start:.5f}")
return returned
return logger
View closure_python.py
def make_incrementer(step):
counter = 0
def incrementer():
nonlocal counter
counter += step
return counter
return incrementer
View st_web_app.py
import streamlit as st
import pandas as pd
st.title("My First Web App")
st.header("Titanic Dataset")
df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv")
st.write(df)
View spm_classes.py
>>> class Student:
... def __init__(self, name):
... self.name = name
...
...
>>> class Teacher:
... def __init__(self, name):
... self.name = name
...
...