Skip to content

Commit

Permalink
Merge pull request #537 from realpython/python-built-in-functions
Browse files Browse the repository at this point in the history
Sample code for the article on built-in functions
  • Loading branch information
brendaweles authored Jun 27, 2024
2 parents 53c2052 + 69849c1 commit 96e5467
Show file tree
Hide file tree
Showing 27 changed files with 376 additions and 0 deletions.
3 changes: 3 additions & 0 deletions python-built-in-functions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python's Built-in Functions: A Complete Exploration

This folder provides the code examples for the Real Python tutorial [Python's Built-in Functions: A Complete Exploration](https://realpython.com/python-built-in-functions/).
11 changes: 11 additions & 0 deletions python-built-in-functions/birds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Duck:
def fly(self):
print("The duck is flying")

def swim(self):
print("The duck is swimming")


class Pigeon:
def fly(self):
print("The pigeon is flying")
17 changes: 17 additions & 0 deletions python-built-in-functions/calculations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
functions = [
"def add(a, b): return a + b",
"def subtract(a, b): return a - b",
"def multiply(a, b): return a * b",
"def divide(a, b): return a / b",
]


for function in functions:
exec(function)


# Uncomment the following lines
# print(add(1, 2))
# print(subtract(3, 2))
# print(multiply(2, 3))
# print(divide(6, 3))
20 changes: 20 additions & 0 deletions python-built-in-functions/circle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from time import sleep

SENTINEL = object()


class Circle:
def __init__(self, radius):
self.radius = radius
self._diameter = SENTINEL

@property
def diameter(self):
if self._diameter is SENTINEL:
sleep(0.5) # Simulate a costly computation
self._diameter = self.radius * 2
return self._diameter


circle = Circle(5)
print(circle.diameter)
28 changes: 28 additions & 0 deletions python-built-in-functions/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class CommandProcessor:
def __init__(self):
self.commands = {}

def register_command(self, command):
if not callable(command):
raise ValueError("command is not callable")
self.commands[command.__name__] = command

def execute_command(self, name, *args, **kwargs):
if (command := self.commands.get(name)) is None:
raise ValueError(f"command '{name}' not found")
return command(*args, **kwargs)


def add(a, b):
return a + b


subtract = 3 - 2


command_processor = CommandProcessor()
command_processor.register_command(add)
command_processor.register_command(subtract)

print(command_processor.execute_command("add", 1, 2))
print(command_processor.register_command(subtract))
5 changes: 5 additions & 0 deletions python-built-in-functions/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"DATABASE_URL": "postgres://user:pass@localhost/dbname",
"DEBUG_MODE": true,
"MAX_CONNECTIONS": 10
}
12 changes: 12 additions & 0 deletions python-built-in-functions/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import json


def load_config(config_file):
with open(config_file) as file:
config = json.load(file)

globals().update(config)


load_config("config.json")
print(globals())
7 changes: 7 additions & 0 deletions python-built-in-functions/evaluator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def evaluator(expression):
numbers = [2, 3, 4, 5]
n = len(numbers)
return eval(expression, {}, {"numbers": numbers, "n": n})


print(evaluator("sum(numbers) / n + 100")) # 3.5
21 changes: 21 additions & 0 deletions python-built-in-functions/factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
def create_class(name, custom_members):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

def __repr__(self):
return f"{name}({self.__dict__})"

class_members = {
"__init__": __init__,
"__repr__": __repr__,
}
class_members.update(custom_members)

return type(name, (), class_members)


User = create_class("User", {"name": "", "age": 0, "email": ""})
Product = create_class("Product", {"name": "", "price": 0.0, "units": 0})

john = User(name="John", age=30, email="[email protected]")
table = Product(name="Table", price=200.0, units=5)
12 changes: 12 additions & 0 deletions python-built-in-functions/fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Fibonacci:
def __init__(self):
self._cache = [0, 1]

def __call__(self, index):
if index < len(self._cache):
fib_number = self._cache[index]
print(f"{fib_number} id = {id(fib_number)}")
else:
fib_number = self(index - 1) + self(index - 2)
self._cache.append(fib_number)
return fib_number
2 changes: 2 additions & 0 deletions python-built-in-functions/files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
with open("fruits.txt") as file:
print(file.read())
8 changes: 8 additions & 0 deletions python-built-in-functions/formatting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Formatter:
@staticmethod
def as_currency(value):
return f"${value:,.2f}"

@staticmethod
def as_percent(value):
return f"{value:.2%}"
18 changes: 18 additions & 0 deletions python-built-in-functions/guess.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from random import randint

LOW, HIGH = 1, 10

secret_number = randint(LOW, HIGH)
clue = ""

while True:
guess = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
number = int(guess)
if number > secret_number:
clue = f"(less than {number})"
elif number < secret_number:
clue = f"(greater than {number})"
else:
break

print(f"You guessed it! The secret number is {number}")
5 changes: 5 additions & 0 deletions python-built-in-functions/mean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def mean(values):
try:
return sum(values) / len(values)
except ZeroDivisionError:
raise ValueError("mean() arg shouldn't be empty") from None
9 changes: 9 additions & 0 deletions python-built-in-functions/menu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def list_menu(options):
print("Main Menu:")
for index, option in enumerate(options, start=1):
print(f"{index}. {option}")


# Example usage
menu_options = ["Open", "Save", "Settings", "Quit"]
list_menu(menu_options)
9 changes: 9 additions & 0 deletions python-built-in-functions/person.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Person:
def __init__(self, name, age):
self.name = name
self.age = age


jane = Person("Jane", 25)
print(getattr(jane, "name"))
print(getattr(jane, "age"))
14 changes: 14 additions & 0 deletions python-built-in-functions/point.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import math


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

@classmethod
def from_polar(cls, distance, angle):
return cls(
x=distance * math.cos(math.radians(angle)),
y=distance * math.sin(math.radians(angle)),
)
27 changes: 27 additions & 0 deletions python-built-in-functions/point_v1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# class Point:
# def __init__(self, x, y):
# self.x = x
# self.y = y


class Point:
def __init__(self, x, y):
self.set_x(x)
self.set_y(y)

def get_x(self):
return self._x

def set_x(self, x):
self._x = self.validate(x)

def get_y(self):
return self._y

def set_y(self, y):
self._y = self.validate(y)

def validate(self, value):
if not isinstance(value, int | float):
raise ValueError("coordinates must be numbers")
return value
25 changes: 25 additions & 0 deletions python-built-in-functions/point_v2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

@property
def x(self):
return self._x

@x.setter
def x(self, value):
self._x = self.validate(value)

@property
def y(self):
return self._y

@y.setter
def y(self, value):
self._y = self.validate(value)

def validate(self, value):
if not isinstance(value, int | float):
raise ValueError("coordinates must be numbers")
return value
13 changes: 13 additions & 0 deletions python-built-in-functions/powers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import timeit

base = 2
exp = 1000000
mod = 1000000

print(
timeit.timeit("pow(base, exp) % mod", globals=globals(), number=10) * 1000
)

print(
timeit.timeit("pow(base, exp, mod)", globals=globals(), number=10) * 1000
)
45 changes: 45 additions & 0 deletions python-built-in-functions/processors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import csv
import json


class CSVProcessor:
def __init__(self, filename):
self.filename = filename

def read(self):
with open(self.filename, encoding="utf-8", newline="") as file:
return list(csv.DictReader(file))

def write(self, data):
with open(
self.filename, mode="w", encoding="utf-8", newline=""
) as file:
writer = csv.DictWriter(file, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)


class JSONProcessor:
def __init__(self, filename):
self.filename = filename

def read(self):
with open(self.filename, encoding="utf-8") as file:
return json.load(file)

def write(self, data):
with open(self.filename, mode="w", encoding="utf-8") as file:
json.dump(data, file, indent=2)


class FileProcessor:
def __init__(self, filename, processor):
self.filename = filename
self.processor = processor(filename)

def __getattr__(self, attr):
return getattr(self.processor, attr)


file_proc = FileProcessor("products.csv", CSVProcessor)
print(file_proc.read())
6 changes: 6 additions & 0 deletions python-built-in-functions/products.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
product,price,sold_units
Laptop,1200,30
Phone,700,50
Tablet,450,100
Desktop,1000,20
Monitor,300,50
16 changes: 16 additions & 0 deletions python-built-in-functions/progress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
def progress(percent=0, width=30):
end = ""
if percent == 100:
end = "\n"
left = width * percent // 100
right = width - left
print(
"\r[",
"#" * left,
" " * right,
"]",
f" {percent:.0f}%",
sep="",
end=end,
flush=True,
)
7 changes: 7 additions & 0 deletions python-built-in-functions/reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def read_user_input():
print("Enter word (type 'done' to finish):")
for word in iter(input, "done"):
print(f"Processing word: '{word}'")


read_user_input()
15 changes: 15 additions & 0 deletions python-built-in-functions/shapes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

def perimeter(self):
return 2 * (self.length + self.width)


class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
12 changes: 12 additions & 0 deletions python-built-in-functions/stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Stack:
def __init__(self, items=None):
self.items = list(items) if items is not None else []

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

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

def __bool__(self):
return bool(self.items)
Loading

0 comments on commit 96e5467

Please sign in to comment.