Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample code for the article on closures #581

Merged
merged 7 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-closure/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python Closures: Common Use Cases and Examples

This folder provides the code examples for the Real Python tutorial [Python Closures: Common Use Cases and Examples](https://realpython.com/python-closure/).
25 changes: 25 additions & 0 deletions python-closure/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import tkinter as tk

app = tk.Tk()
app.title("GUI App")
app.geometry("320x240")

label = tk.Label(app, font=("Helvetica", 16, "bold"))
label.pack()


def callback(text):
def closure():
label.config(text=text)

return closure


button = tk.Button(
app,
text="Greet",
command=callback("Hello, World!"),
)
button.pack()

app.mainloop()
8 changes: 8 additions & 0 deletions python-closure/appender.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def make_appender():
items = []

def appender(new_item):
items.append(new_item)
return items

return appender
16 changes: 16 additions & 0 deletions python-closure/closure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# def outer_func():
# name = "Pythonista"

# def inner_func():
# print(f"Hello, {name}!")

# return inner_func


def outer_func():
name = "Pythonista"
return lambda: print(f"Hello, {name}!")


inner_func = outer_func()
inner_func()
9 changes: 9 additions & 0 deletions python-closure/counter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def make_counter():
count = 0

def counter():
nonlocal count
count += 1
return count

return counter
8 changes: 8 additions & 0 deletions python-closure/cum_average.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def cumulative_average():
data = []

def average(value):
data.append(value)
return sum(data) / len(data)

return average
12 changes: 12 additions & 0 deletions python-closure/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def decorator(function):
def closure():
print("Doing something before calling the function.")
function()
print("Doing something after calling the function.")

return closure


@decorator
def greet():
print("Hi, Pythonista!")
11 changes: 11 additions & 0 deletions python-closure/free_variables.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def outer_func(outer_arg):
local_var = "Outer local variable"

def closure():
print(outer_arg)
print(local_var)
print(another_local_var)

another_local_var = "Another outer local variable"

return closure
7 changes: 7 additions & 0 deletions python-closure/inner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def outer_func():
name = "Pythonista"

def inner_func():
print(f"Hello, {name}!")

inner_func()
27 changes: 27 additions & 0 deletions python-closure/memoization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from time import sleep
from timeit import timeit


def memoize(function):
cache = {}

def closure(number):
if number not in cache:
cache[number] = function(number)
return cache[number]

return closure


@memoize
def slow_operation(number):
sleep(0.5)


exec_time = timeit(
"[slow_operation(number) for number in [2, 3, 4, 2, 3, 4]]",
globals=globals(),
number=1,
)

print(f"Slow operation's time: {exec_time:.2f} seconds.")
28 changes: 28 additions & 0 deletions python-closure/roots.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
def make_root_calculator(root_degree, precision=2):
def root_calculator(number):
return round(pow(number, 1 / root_degree), precision)

return root_calculator


square_root = make_root_calculator(2, 4)
print(square_root(42))

cubic_root = make_root_calculator(3, 2)
print(cubic_root(42))


class RootCalculator:
def __init__(self, root_degree, precision=2):
self.root_degree = root_degree
self.precision = precision

def __call__(self, number):
return round(pow(number, 1 / self.root_degree), self.precision)


square_root = RootCalculator(2, 4)
print(square_root(42))

cubic_root = RootCalculator(3, 2)
print(cubic_root(42))
12 changes: 12 additions & 0 deletions python-closure/stack_v1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Stack:
def __init__(self):
self._items = []

def push(self, item):
self._items.append(item)

def pop(self):
return self._items.pop()

def __str__(self):
return str(self._items)
15 changes: 15 additions & 0 deletions python-closure/stack_v2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
def Stack():
_items = []

def push(item):
_items.append(item)

def pop():
return _items.pop()

def closure():
pass

closure.push = push
closure.pop = pop
return closure
Loading