Miscellaneous Python Notes¶
Python HTTP Server¶
To spin up an http server, you can use python3 -m http.server to serve a
directory over HTTP (port 80).
To specify a different port, you can use python3 -m http.server 8080 to serve on port 8080.
Containerizing an Application¶
To safely share with others, you can containerize an application.
Use podman or docker to build the image:
# Use the Python version you need
#FROM python:3.9-slim
FROM python:3.11
# Set the working directory inside the container
WORKDIR /usr/src/app
# Copy the current directory into the container at the WORKDIR
COPY . .
# Install dependencies (expects a requirements.txt file in the current directory)
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world (for web apps)
EXPOSE 80
# Set environment variables
ENV NAME World
ENV PATH /usr/src/app
# Run the app when the container launches
RUN ["python3", "./app.py"]
Expanding Iterables for Function Arguments¶
The * operator can be used to expand iterables into function arguments or to
unpack elements from lists, tuples, or other iterable objects.
With dictionaries, the ** operator can be used to unpack key-value pairs into
function arguments.
Some examples:
# Expanding a list into function arguments
numbers = [1, 2, 3]
def add(a, b, c):
print(a + b + c)
add(*numbers) # Expands into `add(1, 2, 3)`
# Expanding a tuple into function arguments
coordinates = (4, 5)
def print_coordinates(x, y):
print(f"Coordinates: ({x}, {y})")
print_coordinates(*coordinates) # Expands into `print_coordinates(4, 5)`
# Expanding a dictionary into function arguments
person = {'name': 'Alice', 'age': 30}
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet(**person) # Expands into `greet(name='Alice', age=30)`
When using a function that accepts variable-length arguments, you can
use *args and **kwargs to handle additional positional and keyword
arguments, respectively.