Skip to content

Instantly share code, notes, and snippets.

View nenetto's full-sized avatar
🦊
Keep learning & 🐝 kind

nenetto nenetto

🦊
Keep learning & 🐝 kind
View GitHub Profile
@nenetto
nenetto / iterator_tools.py
Created September 26, 2023 10:38
Itertools
import itertools
# Linking iterators together
# chain: Combines multiple iterators into a single sequential iterator.
# cycle: Repeats an iterator’s items forever.
# tee: Splits a single iterator into multiple parallel iterators.
# zip_longest: A variant of the zip built-in function that works well with iterators of different lengths.
# Filtering items from an iterator
@nenetto
nenetto / heapq_module.py
Created September 26, 2023 10:34
Heap Queue & Bisection
# heaps in standard list types with functions like heappush, heappop, and nsmallest
# Items are always removed by highest priority (lowest number) first.
a = []
heappush(a, 5)
heappush(a, 3)
heappush(a, 7)
heappush(a, 4)
# print(heappop(a), heappop(a), heappop(a), heappop(a))
@nenetto
nenetto / deque_example.py
Created September 26, 2023 10:31
Double-ended Queue, Ordered dictionaries, default dictionary
# Double-ended Queue
fifo = collections.deque()
fifo.append(1) # Producer
x = fifo.popleft() # Consumer
# OrderedDict
a = OrderedDict()
a[‘foo’] = 1
a[‘bar’] = 2
@nenetto
nenetto / datetime_example.py
Created September 26, 2023 10:24
Datetime and zone conversions
from datetime import datetime, timezone
# Conversion to computer local time
now = datetime(2014, 8, 10, 18, 18, 30)
now_utc = now.replace(tzinfo=timezone.utc)
now_local = now_utc.astimezone()
print(now_local)
# Conversion local to Unix timestamp in UTC
time_str = '2014-08-10 11:18:30'
@nenetto
nenetto / contextlib_with_example.py
Created September 26, 2023 10:20
Contextlib and with
@contextmanager
def debug_logging(level):
""" Change the logging level
"""
logger = logging.getLogger()
old_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
yield
@nenetto
nenetto / decorators_example.py
Created September 26, 2023 10:14
Decorator using wrapper
def trace_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Decorate before
print('Hello')
# Call function
result = func(*args, **kwargs)
@nenetto
nenetto / multiprocessing_example.py
Created September 26, 2023 08:03
Multiprocessing and concurrent.futures
def gcd(pair):
a, b = pair
low = min(a, b)
for i in range(low, 0, -1):
if a % i == 0 and b % i == 0:
return i
# No parallel
numbers = [(1963309, 2265973), (2030677, 3814172),
(1551645, 2229620), (2039045, 2020802)]
@nenetto
nenetto / corutines_examples.py
Created September 26, 2023 07:56
Python Corutines
# Corutines
# Extension of generators
# They serve like "microservices"
def my_corutine():
while True: # Alive microservice
received_value = yield # This will freeze the corutine until a value is "send" to it
# Do amazing work
print("Job done with input", received_value)
@nenetto
nenetto / threads.py
Last active September 26, 2023 07:37
Python Threads: avoid blocking I/O NO FOR PARALLELISM (GIL ISSUE)
class LockingCounter(object):
def __init__(self):
self.lock = Lock()
self.count = 0
def increment(self, offset):
with self.lock:
self.count += offset
def worker(sensor_index, how_many, counter):
for _ in range(how_many):
@nenetto
nenetto / subprocess.py
Created September 26, 2023 07:32
Python subprocesses
def run_openssl(data):
env = os.environ.copy()
env[‘password’] = b’\xe24U\n\xd0Ql3S\x11’
proc = subprocess.Popen(
[‘openssl’, ‘enc’, ‘-des3’, ‘-pass’, ‘env:password’],
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
proc.stdin.write(data)
proc.stdin.flush() # Ensure the child gets input