Skip to content

Instantly share code, notes, and snippets.

View pandas_combine.py
>>> def taking_larger_square(s1, s2):
... return s1 * s1 if s1.sum() > s2.sum() else s2 * s2
>>> df0.combine(df1.rename(columns={"c": "a", "d": "b"}), taking_larger_square)
a b
0 4 25
1 9 36
2 16 49
View pandas_data_dfs.py
>>> import pandas as pd
>>> df0 = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
>>> df0
a b
0 1 4
1 2 5
2 3 6
>>> df1 = pd.DataFrame({"c": [2, 3, 4], "d": [5, 6, 7]})
>>> df1
c d
View function_async_used.py
>>> import asyncio
>>> async def login_user_async():
... await asyncio.sleep(2)
...
>>> async def load_posts_async():
... await asyncio.sleep(3)
...
>>> async def launch_app_async():
... print("Open App:", time.asctime())
... await asyncio.gather(
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