### Setup and Contribute to Python Cheatsheet Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/src/pages/contributing.md Steps to set up the Python cheatsheet project locally, including installing pnpm, cloning the repository, installing dependencies, creating a branch, making changes, and pushing them for a pull request. ```Shell curl -fsSL https://get.pnpm.io/install.sh | sh - ``` ```Shell iwr https://get.pnpm.io/install.ps1 -useb | iex ``` ```Shell git clone https://github.com/wilfredinni/python-cheatsheet.git cd python-cheatsheet pnpm install ``` ```Shell git branch fix_bug git checkout fix_bug ``` ```Shell git add . git commit -m 'succinct explanation of what changed' git push origin fix_bug ``` -------------------------------- ### Initialize a new project interactively Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md For existing projects, `poetry init` can be used to interactively create a `pyproject.toml` file, guiding the user through project metadata and dependency setup. ```shell poetry init ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Installs all dependencies listed in the `pyproject.toml` file for the current project. This command is used to set up the project environment after cloning or when starting work. ```Shell poetry install ``` -------------------------------- ### Interactive Python Shell Usage Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-3.md Demonstrates how to use the timer decorator in an interactive Python session after installing the package. ```python >>> from how_long import timer >>> >>> @timer ... def test_function(): ... [i for i in range(10000)] ... >>> test_function() Execution Time: 705 ms. ``` -------------------------------- ### Install Poetry with pip Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md Installs the Poetry dependency management tool using pip. This is a quick way to get started, though the official installer is recommended for better isolation. ```shell pip install poetry ``` -------------------------------- ### Install Python Package with setup.py Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/setup-py.md This command installs a Python package using its `setup.py` script. It's a common way to manage local installations or packages not yet published to PyPI. Ensure you are in the root directory of the package. ```bash python setup.py install ``` -------------------------------- ### Manage Tools with UVX and UV Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-uv-package-manager.md Demonstrates running tools without explicit installation using `uvx` and installing tools globally with `uv tool install`. ```bash # Run tools without installation $ uvx ruff check # Install tools globally $ uv tool install ruff ``` -------------------------------- ### Set Comprehension Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-comprehensions-step-by-step.md Provides an example of creating a new set with uppercase elements from an existing set using a for loop, and then shows the equivalent, more concise set comprehension syntax. ```python >>> my_set = {"abc", "def"} >>> # Here, we create a new set with uppercase elements with a for loop >>> new_set = set() >>> for s in my_set: ... new_set.add(s.upper()) >>> print(new_set) # {'ABC', 'DEF'} ``` ```python >>> my_set = {"abc", "def"} >>> new_set = {s.upper() for s in my_set} >>> print(new_set) # {'ABC', 'DEF'} ``` -------------------------------- ### Python Tuple Use Cases Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Provides examples of practical scenarios where tuples are beneficial, such as defining constants, representing fixed data like RGB colors, and using them as dictionary keys due to their immutability. ```python # Good use cases WINDOW_SIZE = (800, 600) # Constants DEFAULT_COLOR = (255, 255, 255) # RGB white # Dictionary with tuple keys locations = { (0, 0): "origin", (1, 1): "northeast", (-1, -1): "southwest" } ``` -------------------------------- ### Install Poetry with official installer Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md Installs Poetry using its official installer script, which is the recommended method for isolating Poetry's dependencies from the system. This allows for easy updates via `poetry self update`. ```shell curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md Installs all packages defined in the pyproject.toml file, creating a virtual environment if one doesn't exist. This command is crucial after initializing a project or cloning a repository to set up the development environment. ```shell $ poetry install ``` -------------------------------- ### Python Project README Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-3.md Shows an example of a README file for a Python project, including a description and a code block demonstrating the usage of the `timer` decorator. This is typically written in reStructuredText (rst) format. ```rst how_long ======== Simple Decorator to measure a function execution time. Example _______ .. code-block:: python from how_long import timer @timer def some_function(): return [x for x in range(10_000_000)] ``` -------------------------------- ### Install Anyconfig Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/json-yaml.md Shows the bash command to install the `anyconfig` package, a utility for abstracting configuration file formats like JSON, YAML, and TOML. ```bash pip install anyconfig ``` -------------------------------- ### Python Numbers: int, float, complex Examples Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Demonstrates the creation and basic usage of Python's integer (`int`), floating-point (`float`), and complex (`complex`) number types. It shows literal definitions and simple arithmetic operations, highlighting potential precision issues with floats. ```python # Integers - whole numbers age = 25 score = 100 negative = -10 # Floats - numbers with decimals price = 19.99 temperature = 98.6 pi = 3.14159 # Complex - numbers with real and imaginary parts (advanced math) z = 2 + 3j # j represents the imaginary unit in Python # Working with integers items = 5 total_items = items * 3 # 15 # Working with floats radius = 2.5 area = 3.14159 * radius * radius # 19.634... # Be careful with float precision result = 0.1 + 0.2 # 0.30000000000000004 (not exactly 0.3!) # Complex numbers (you probably won't need these as a beginner) z = complex(2, 3) # Same as 2+3j magnitude = abs(z) # 3.605... ``` -------------------------------- ### Basic UV Package Management Commands Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-uv-package-manager.md Demonstrates fundamental commands for managing Python packages using UV, including installing individual packages and installing from a requirements file. ```bash # Install packages $ uv pip install requests ``` ```bash # Install from requirements file $ uv pip install -r requirements.txt ``` ```bash # List installed packages $ uv pip list ``` -------------------------------- ### Python help() function examples Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/builtin/help.md Demonstrates how to use the Python `help()` built-in function to get documentation for various objects like types, classes, and the `help()` function itself. The output shown is typical for an interactive Python session. ```python >>> help(type) # Help on class type in module builtins: # class type(object) # | type(object_or_name, bases, dict) # | type(object) -> the object's type # | type(name, bases, dict) -> a new type # | # | Methods defined here: # | # | __call__(self, /, *args, **kwargs) # | Call self as a function. # | # | __delattr__(self, name, /) # | Implement delattr(self, name). # | # | __dir__(self, /) # | Specialized __dir__ implementation for types. # | # | __getattribute__(self, name, /) # : ``` ```python >>> help(str) # Help on class str in module builtins: # class str(object) # | str(object='') -> str # | str(bytes_or_buffer[, encoding[, errors]]) -> str # | # | Create a new string object from the given object. If encoding or # | errors is specified, then the object must expose a data buffer # | that will be decoded using the given encoding and error handler. # | Otherwise, returns the result of object.__str__() (if defined) # | or repr(object). # | encoding defaults to sys.getdefaultencoding(). # | errors defaults to 'strict'. # | # | Methods defined here: # : ``` ```python >>> help(help) # Help on _Helper in module _sitebuiltins object: # class _Helper(builtins.object) # | Define the builtin 'help'. # | # | This is a wrapper around pydoc.help that provides a helpful message # | when 'help' is typed at the Python interactive prompt. # | # | Calling help() at the Python prompt starts an interactive help session. # | Calling help(thing) prints help for the python object 'thing'. # | # | Methods defined here: # | # | __call__(self, *args, **kwds) # | Call self as a function. # | # : ``` -------------------------------- ### UV Python Version Management Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-uv-package-manager.md Illustrates how to use UV to manage Python installations, specifically focusing on installing different Python versions. ```bash # Install Python versions $ uv python install 3.12 ``` -------------------------------- ### Install Ruamel.yaml Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/json-yaml.md Provides the bash command to install the Ruamel.yaml library, which is recommended for better YAML specification compliance and comment preservation. ```bash pip install ruamel.yaml ``` -------------------------------- ### Install UV Package Manager Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-uv-package-manager.md Provides instructions for installing UV using various methods, including shell scripts for Linux/macOS, PowerShell for Windows, and package managers like pip, pipx, and Homebrew. ```bash # Using curl (Linux/macOS) $ curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell # Using PowerShell (Windows) $ powershell -c "irm https://astral.sh/uv/install.ps1 | iex" ``` ```bash # Using pip or pipx $ pip install uv $ pipx install uv ``` ```bash # Using Homebrew (macOS) $ brew install uv ``` -------------------------------- ### Install Poetry (Python Package Manager) Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Installs Poetry, a modern dependency management and packaging tool for Python. It helps declare project dependencies and manage them efficiently. ```Shell pip install --user poetry ``` -------------------------------- ### Python Number Formatting Examples Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/string-formatting.md Demonstrates various Python number formatting techniques using f-strings for controlling decimal places, signs, padding, alignment, and separators. Includes examples for percentage and exponent notation. ```python print(f"{{3.1415926:.2f}}") # Output: 3.14 ``` ```python print(f"{{-1:+.2f}}") # Output: -1.00 ``` ```python print(f"{{2.71828:.0f}}") # Output: 3 ``` ```python print(f"{{4:0>2d}}") # Output: 04 ``` ```python print(f"{{4:x<4d}}") # Output: 4xxx ``` ```python print(f"{{10:x<4d}}") # Output: 10xx ``` ```python print(f"{{1000000:,}}") # Output: 1,000,000 ``` ```python print(f"{{0.35:.2%}}") # Output: 35.00% ``` ```python print(f"{{1000000000:.2e}}") # Output: 1.00e+09 ``` ```python print(f"{{11:11d}}") # Output: 11 ``` ```python print(f"{{11:<11d}}") # Output: 11 ``` ```python print(f"{{11:^11d}}") # Output: 11 ``` -------------------------------- ### Basic Python setup.py Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/setup-py.md A minimal `setup.py` file for a Python package. It defines essential metadata such as the package name, version, the Python packages to include, license, and a long description read from a README file. This script is used by Distutils to build and distribute the package. ```python from distutils.core import setup setup( name='pythonCheatsheet', version='0.1', packages=['pipenv',], license='MIT', long_description=open('README.txt').read(), ) ``` -------------------------------- ### Get Relative Paths with os.path and pathlib Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/file-directory-path.md Illustrates how to calculate the relative path from a starting directory to a target path. Examples include os.path.relpath() and Path.relative_to(). ```python >>> import os >>> os.path.relpath('/etc/passwd', '/') 'etc/passwd' ``` ```python from pathlib import Path print(Path('/etc/passwd').relative_to('/')) # etc/passwd ``` -------------------------------- ### Start New Project with UV Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-uv-package-manager.md Steps to initialize a new Python project, add dependencies, and run commands within the project's isolated environment using `uv`. ```bash # Initialize a new project $ uv init example # Navigate to project directory $ cd example # Add dependencies $ uv add ruff # Run commands in the project environment $ uv run ruff check ``` -------------------------------- ### Python itertools.count() Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/modules/itertools-module.md Creates an iterator that returns evenly spaced values starting from a specified number. It accepts optional 'start' and 'step' arguments. ```python >>> for i in itertools.count(10,3): ... print(i) ... if i > 20: ... break ... # 10 # 13 # 16 # 19 # 22 ``` -------------------------------- ### Get Relative Path Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/modules/pathlib-module.md Illustrates how to obtain a relative path from a starting path to a target path using the `relative_to()` method. This is useful for expressing paths in a more concise way. ```python from pathlib import Path print(Path('/etc/passwd').relative_to('/')) ``` -------------------------------- ### Python Dictionary Creation and Basic Access Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Demonstrates how to create dictionaries using key-value pairs, access values by key, and use the .get() method for safer access, including providing default values. ```python # Creating dictionaries person = {"name": "Alice", "age": 30, "city": "New York"} grades = {"math": 85, "english": 92, "science": 78} empty = {} # Accessing values name = person["name"] # "Alice" age = person.get("age") # 30 (safer way) height = person.get("height", "unknown") # "unknown" if key doesn't exist ``` -------------------------------- ### Python Character Counting Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Demonstrates how to count character occurrences in a string using a dictionary in Python. It iterates through the string, updating counts for each character. ```python # Counting example text = "hello world" char_count = {} for char in text: char_count[char] = char_count.get(char, 0) + 1 # Result: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1} ``` -------------------------------- ### Poetry Command Summary Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md A reference table of common Poetry commands for project initialization, dependency management, and environment setup. ```APIDOC Poetry Commands: poetry new [package-name] - Description: Starts a new Python Project. poetry init - Description: Creates a pyproject.toml file interactively. poetry install - Description: Installs the packages inside the pyproject.toml file. poetry add [package-name] - Description: Adds a package to a Virtual Environment. poetry add -D [package-name] - Description: Adds a dev package to a Virtual Environment. poetry remove [package-name] - Description: Removes a package from a Virtual Environment. poetry remove -D [package-name] - Description: Removes a dev package from a Virtual Environment. poetry self:update - Description: Updates poetry to the latest stable version. ``` -------------------------------- ### Get Relative Path with os.path.relpath Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/modules/os-module.md Shows how to compute a relative path from a starting directory to a target path using os.path.relpath(). This is useful for expressing paths concisely or when moving between directories. ```python import os print(os.path.relpath('/etc/passwd', '/')) # 'etc/passwd' ``` -------------------------------- ### UV Project Setup and Dependency Management Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Commands for initializing a new project with UV, adding dependencies, and running scripts within the project's environment. ```shell uv init my-project cd my-project ``` ```shell uv add requests ``` ```shell uv run python script.py ``` -------------------------------- ### Python type() Examples Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/builtin/type.md This snippet shows how to use the built-in Python `type()` function to get the type of different data types like strings, integers, floats, lists, tuples, sets, and dictionaries. ```python >>> type('span') # ``` ```python >>> type(99) # ``` ```python >>> type(1.1) # ``` ```python >>> type([1, 2]) # ``` ```python >>> type((1, 2)) # ``` ```python >>> type({1, 2}) # ``` ```python >>> type({'a': 1, 'b': 2}) # ``` -------------------------------- ### Package Initialization and Version Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-3.md Defines the package's entry point by importing the timer decorator and sets the package version. ```python from .how_long import timer __version__ = "0.1.1" ``` -------------------------------- ### Python sum() Function Examples Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/builtin/sum.md Demonstrates the usage of Python's built-in sum() function to calculate the total of items in an iterable. The function takes an iterable of numbers and an optional start value, returning their sum. ```python >>> sum([2, 4, 6]) # 12 >>> sum([10, 10, 10]) # 30 ``` -------------------------------- ### Python Set Creation and Initialization Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Shows how to create sets in Python, including initializing with elements, creating an empty set using `set()`, and converting lists to sets to automatically remove duplicates. ```python # Creating sets colors = {"red", "green", "blue"} numbers = {1, 2, 3, 4, 5} empty = set() # Note: {} creates an empty dict, not set! # From lists (removes duplicates) mixed_list = [1, 2, 2, 3, 3, 3] unique_numbers = set(mixed_list) # {1, 2, 3} ``` -------------------------------- ### Python List Common Operations Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Covers essential list manipulation techniques including adding items (append, insert, extend), removing items (remove, pop), and checking for item existence. Also shows how to get the length of a list. ```python shopping_list = ["milk", "bread"] # Adding items shopping_list.append("eggs") # ["milk", "bread", "eggs"] shopping_list.insert(0, "butter") # ["butter", "milk", "bread", "eggs"] shopping_list.extend(["cheese", "ham"]) # Add multiple items # Removing items shopping_list.remove("milk") # Remove first occurrence last_item = shopping_list.pop() # Remove and return last item first_item = shopping_list.pop(0) # Remove and return first item # Useful operations length = len(shopping_list) has_bread = "bread" in shopping_list # Processing lists grades = [85, 92, 78, 96] total = sum(grades) average = total / len(grades) for item in ["wash dishes", "walk dog", "study Python"]: print(f"Task: {item}") ``` -------------------------------- ### Poetry Project Structure Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Illustrates the typical directory structure created by `poetry new`. It includes the project root, source code directory, tests directory, and the crucial `pyproject.toml` file. ```Text my-project ├── pyproject.toml ├── README.rst ├── poetry_demo │ └── __init__.py └── tests ├── __init__.py └── test_poetry_demo.py ``` -------------------------------- ### Python random.uniform() - Random Float in Range Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/modules/random-module.md Returns a random floating point number N such that start <= N <= end for start <= end and end <= N <= start for end < start. The endpoint may or may not be included in the range. ```python >>> random.uniform(1, 5) # 3.697943322009309 ``` -------------------------------- ### Python Tuple Basics and Creation Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Illustrates the creation of tuples in Python, including single-item tuples and the optional use of parentheses. It also shows how to access tuple elements by index. ```python # Creating tuples coordinates = (10, 20) rgb_color = (255, 0, 128) single_item = (42,) # Note the comma for single-item tuples empty = () # Parentheses are often optional point = 5, 10 # Same as (5, 10) name_age = "Alice", 25 # Same as ("Alice", 25) # Accessing items (same as lists) x = coordinates[0] # 10 y = coordinates[1] # 20 ``` -------------------------------- ### Create a new project with Poetry Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md Initializes a new Python project with a standard directory structure managed by Poetry. The command `poetry new [project_name]` creates the project files and a `pyproject.toml`. ```shell poetry new how-long ``` -------------------------------- ### UV Package Manager Installation Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Methods to install the UV package manager, a fast drop-in replacement for pip. Installation can be done via curl for Linux/macOS or using pip. ```shell # Using curl (Linux/macOS) curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```shell # Using pip or pipx pip install uv ``` -------------------------------- ### Poetry pyproject.toml Configuration Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Shows an example of the `pyproject.toml` file used by Poetry. This file defines project metadata, dependencies (both runtime and development), and build system configurations. ```TOML [tool.poetry] name = "my-project" version = "0.1.0" description = "" authors = ["your name "] [tool.poetry.dependencies] python = "*" [tool.poetry.dev-dependencies] pytest = "^3.4" ``` -------------------------------- ### Python range() with start and stop parameters Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/builtin/range.md Shows how to use `range()` with both `start` and `stop` parameters. The loop begins at the `start` value (inclusive) and ends before the `stop` value (exclusive). ```python >>> for i in range(1,8): ... print(i) # 1 # 2 # 3 # 4 # 5 # 6 # 7 ``` -------------------------------- ### Install Python 3.14 on Ubuntu Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-3-14-breaking-free-from-gil.md Steps to install Python 3.14 on Ubuntu systems by adding the deadsnakes PPA, updating package lists, and installing the specific version. ```Bash # Add the PPA sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update # Install Python 3.14 sudo apt install python3.14 ``` -------------------------------- ### UV Project and Dependency Management Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-uv-package-manager.md Covers essential commands for initializing new projects, adding dependencies, generating lock files, and synchronizing project environments with UV. ```bash # Create a new project $ uv init my_project ``` ```bash # Add dependencies $ uv add requests ``` ```bash # Create/update lockfile $ uv lock ``` ```bash # Sync dependencies with environment $ uv sync ``` ```bash # Run commands in project environment $ uv run python script.py ``` -------------------------------- ### pyproject.toml configuration Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md The central configuration file for Poetry projects, replacing traditional files like `setup.py` and `requirements.txt`. It manages project metadata, dependencies, build system requirements, and more. ```toml [tool.poetry] name = "how-long" version = "0.1.0" description = "A simple decorator to measure a function execution time." authors = ["wilfredinni "] [tool.poetry.dependencies] python = "^3.7" [tool.poetry.dev-dependencies] pytest = "^3.0" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" ``` -------------------------------- ### Python Built-in: sum() Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/built-in-functions.md Sums start and the items of an iterable. The iterable must contain numbers. The start value defaults to 0. ```python sum([1, 2, 3]) # Output: 6 sum([1, 2, 3], 10) # Output: 16 ``` -------------------------------- ### Poetry Project Management Commands Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-2.md A collection of essential Poetry commands for managing Python projects. These commands cover project initialization, dependency management (adding, removing, updating), and environment activation. ```APIDOC Poetry Commands: poetry new [package-name] - Description: Starts a new Python project with a standard directory structure. - Parameters: - [package-name]: The name for the new Python package. poetry init - Description: Interactively creates a pyproject.toml file for a new or existing project. - Returns: A pyproject.toml file. poetry install - Description: Installs all dependencies listed in the pyproject.toml file into the virtual environment. - Dependencies: pyproject.toml poetry add [package-name] - Description: Adds a specified package to the project's dependencies and installs it. - Parameters: - [package-name]: The name of the package to add. poetry add -D [package-name] - Description: Adds a specified package as a development dependency and installs it. - Parameters: - [package-name]: The name of the development package to add. poetry remove [package-name] - Description: Removes a package from the project's dependencies and uninstalls it. - Parameters: - [package-name]: The name of the package to remove. poetry remove -D [package-name] - Description: Removes a development package from the project's dependencies and uninstalls it. - Parameters: - [package-name]: The name of the development package to remove. poetry update - Description: Updates all project dependencies to their latest compatible versions according to pyproject.toml. - Dependencies: pyproject.toml poetry shell - Description: Activates the project's virtual environment in the current terminal session. ``` -------------------------------- ### Python reversed() Function Example Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/builtin/reversed.md This example shows how to use the built-in reversed() function in Python. It takes a sequence (like a list) and returns an iterator that yields elements in reverse order. The example demonstrates accessing elements using the __next__() method. ```python >>> i = reversed([1, 2, 3]) >>> i.__next__() # 3 >>> i.__next__() # 2 >>> i.__next__() # 1 >>> i # ``` -------------------------------- ### String Slicing in Python Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/manipulating-strings.md Explains string slicing in Python, which extracts a portion (substring) of a string. Slicing uses the syntax `[start:stop:step]`, where `start` is inclusive, `stop` is exclusive, and `step` determines the increment. Omitting `start` defaults to the beginning, `stop` to the end, and `step` to 1. ```python >>> spam = 'Hello world!' >>> spam[0:5] # 'Hello' >>> spam[:5] # 'Hello' >>> spam[6:] # 'world!' >>> spam[6:-1] # 'world' >>> spam[:-1] # 'Hello world' >>> spam[::-1] # '!dlrow olleH' >>> fizz = spam[0:5] >>> fizz # 'Hello' ``` -------------------------------- ### Python List Creation and Basic Access Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Shows how to create lists with various data types, access elements using positive and negative indices, and create empty lists. Lists are ordered and mutable sequences. ```python # Creating lists fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5] mixed = ["hello", 42, True, None] # Lists can hold different types empty = [] # Accessing items (starts at index 0) first_fruit = fruits[0] # "apple" last_fruit = fruits[-1] # "orange" ``` -------------------------------- ### Python random.randint() - Random Integer Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/modules/random-module.md Returns a random integer N such that start <= N <= stop. Both start and stop are included in the range. ```python random.randint(start: int, stop: int) ``` ```python >>> random.randint(1, 5) # 3 ``` -------------------------------- ### Create New Project with Poetry Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Creates a new Python project structure managed by Poetry. This command generates a standard directory layout and a `pyproject.toml` file for project configuration and dependencies. ```Shell poetry new my-project ``` -------------------------------- ### Getting Index and Value with enumerate() Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/lists-and-tuples.md Demonstrates using the `enumerate()` function to loop through a list while simultaneously getting both the index and the value of each item. ```python >>> furniture = ['table', 'chair', 'rack', 'shelf'] >>> for index, item in enumerate(furniture): ... print(f'index: {index} - item: {item}') # index: 0 - item: table # index: 1 - item: chair # index: 2 - item: rack # index: 3 - item: shelf ``` -------------------------------- ### pyproject.toml [tool.poetry.dependencies] section Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md Specifies the production dependencies required for the project, along with their version constraints. It also lists development dependencies separately in `[tool.poetry.dev-dependencies]`. ```toml [tool.poetry.dependencies] python = "^3.7" ... ``` -------------------------------- ### Activating Poetry Shell and Opening VSCode Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-2.md Commands to activate the project's virtual environment using Poetry and then open the current directory in Visual Studio Code. This is a common workflow for setting up the development environment. ```shell $ poetry shell $ code . ``` -------------------------------- ### Python max() function examples Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/builtin/max.md Examples showing how to use the Python built-in max() function to find the largest item in a list and a tuple. ```python >>> max([1, 2, 10, 40, 5]) # 40 >>> max((1, 2, 10, 40, 5)) # 40 ``` -------------------------------- ### Python Tuple Unpacking and Swapping Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-data-types.md Explains how to unpack tuple elements into individual variables and demonstrates the common Python idiom for swapping variable values using tuple assignment. ```python # Unpacking is very useful point = (100, 200) x, y = point # x=100, y=200 # Swapping values a = 5 b = 10 a, b = b, a # Now a=10, b=5 # Function returning multiple values def get_name_age(): return "Bob", 25 name, age = get_name_age() ``` -------------------------------- ### Install virtualenvwrapper-win (Windows) Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Installs virtualenvwrapper-win, a set of extensions to make working with virtualenv environments on Windows more convenient. It provides commands for easier environment management. ```Shell pip install virtualenvwrapper-win ``` -------------------------------- ### Add Pre-release Packages with Poetry Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/blog/python-projects-with-poetry-and-vscode-part-1.md Installs a package that is in a pre-release state (e.g., beta, release candidate). The --allow-prereleases flag is necessary when Poetry cannot find a stable version for the specified package. ```shell $ poetry add -D black --allow-prereleases ``` -------------------------------- ### Install virtualenv (Python) Source: https://github.com/wilfredinni/python-cheatsheet/blob/master/docs/cheatsheet/virtual-environments.md Installs the virtualenv package, a tool for creating isolated Python environments. This is a prerequisite for using virtualenv to manage project dependencies separately. ```Shell pip install virtualenv ```