Skip to content

Instantly share code, notes, and snippets.

View lachlan-eagling's full-sized avatar

Lachlan Eagling lachlan-eagling

  • Sunshine Coast, Australia
View GitHub Profile
@lachlan-eagling
lachlan-eagling / user.go
Last active October 12, 2019 01:38
Blog - Anatomy of a Struct (Basic User Struct)
type User struct {
firstName string
lastName string
username string
age int
}
@lachlan-eagling
lachlan-eagling / type_hint_example.py
Created October 6, 2019 03:43
Blog - Type Hints
from typing import List, Dict
from models import Employee
def process_employees(employees):
employee_dict = {}
for employee in employees:
employee_dict[employee.id] = employee
return employee_dict
def process_employees(employees: List[Employee]) -> Dict[int, Employee]:
@lachlan-eagling
lachlan-eagling / generator_runtime_performance.py
Created October 5, 2019 01:53
Blog - Generators (Runtime Performance)
import cProfile
print("Generator Runtime Stats:")
cProfile.run('sum((i for i in range(100000)))')
print("List Runtime Stats:")
cProfile.run('sum([i for i in range(100000)])')
Generator Runtime Stats:
100005 function calls in 0.123 seconds
@lachlan-eagling
lachlan-eagling / generator_memory.py
Created October 5, 2019 01:52
Blog - Generators (Memory Consumption)
from sys import getsizeof
size = 50_000
generator = (i for i in range(size))
lst = [i for i in range(size)]
print(f"Generator Size: {getsizeof(generator)} bytes")
print(f"List Size: {getsizeof(lst)} bytes")
>>> Generator Size: 112 bytes
@lachlan-eagling
lachlan-eagling / generator_stop_iter.py
Created October 5, 2019 01:52
Blog - Generators (StopIteration)
generator = sequence_generator(3)
try:
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator)) # This call to next will raise an exception.
except StopIteration:
print("Generator exhausted")
@lachlan-eagling
lachlan-eagling / generator_iteration_1.py
Created October 5, 2019 01:50
Blog - Generators (in-depth)
def sequence_generator(n):
for i in range(n):
yield i
generator = sequence_generator(3)
print(next(generator))
>>> 0
for i in generator:
print(i)
@lachlan-eagling
lachlan-eagling / gen_expr.py
Created October 5, 2019 01:48
Blog - Generators (expressions)
for i in (x for x in range(n)):
do_something(i)
@lachlan-eagling
lachlan-eagling / fib_gen.py
Created October 5, 2019 01:47
Blog - Generators (Fibonacci)
def fib_generator(n):
i, j = 0, 1
for _ in range(n):
yield i
i, j = j, i + j
@lachlan-eagling
lachlan-eagling / infinite_seq.py
Created October 5, 2019 01:46
Blog - Generators (Infinite Numbers)
def ininite_number_generator(increment=1):
i := 0
while True:
yield i
i += increment
@lachlan-eagling
lachlan-eagling / read_file_by_chunks.py
Created October 5, 2019 01:45
Blog - Generators (File Generator)
def read_chunks(filename, mode="r", chunk_size=32):
with open(filename, mode) as f:
while True:
data = f.read(chunk_size)
if not data:
break
yield data
def main():