Intro#

This section highlights features and tools in Python that can be used independently of any specific application.

Syntax#

Syntax is set of rules that define the structure and format of valid statements and expressions in a programming language. It dictates how symbols, keywords, and operators must be arranged to create meaningful instructions for the computer. Find out more at the specific page.


Look at the following code:

from random import choice
some_symbol = lambda: choice(["\\", "|", "/"])


print("\n".join([
    ''.join([some_symbol() for i in range(50)])
    for i in range(10)
]))
||/||\||/|\/\/\/|///|/|/|\||||\/|//\\\/////\|/||\\
/|\////\||//||\|||||/|/||///|\//|\///|||\||//|/\||
\|//||//\\/\\|\\||/|/\\///\\\|\\\\\/|/|\|\||||///\
//\///\\|\/|||///|\//|\///\\/\\/|/|\\\/\\\/\\|\||\
||/\/||||/\|\|//|/|/\||\||/\|/|\|//\|/|\|||\|\/\|\
////|/\\\//\\|//|\//\//|\/////\\\\|\\/\/|/////\|\|
|\|/\|//\\/\/|///|////||\\\|\|\|//\|||/\|\|/\||\\\
\/||/\\\|\/|/|\\\|||\\/|/\/|/|\\//||/\\|\|\/|/\\||
/|\\\|\\|\/|/\/|\\|\\|/\\|||//\/\|/\/|\\\/|/|/\///
|/|////|\\/|\///\/|\///||||\|///|\\/\\\/\\||//\/|/

At this short snippet code were used:

Operators:

  1. = - Assignment operator (used in some_symbol = lambda: ...).

  2. : - Used in the lambda function definition (lambda: choice(...)).

  3. [] - List literal and list comprehension syntax (["\\", "|", "/"], [some_symbol() for i in range(50)], and [... for i in range(10)]).

  4. () - Parentheses for function calls and grouping expressions (choice(...), some_symbol(), and range(...)).

  5. . - Attribute access (used in "\n".join(...) and ''.join(...)).

  6. for - Part of the for loop in list comprehensions.

  7. in - Used in the context of the for loop within the list comprehensions.

Literals:

  1. "\\", "|", "/" - String literals representing the symbols in the list.

  2. \n - String literal for a newline character.

  3. '' - Empty string literal.

  4. 50, 10 - Integer literals used as arguments to range().

Keywords:

  1. from - Used for importing specific parts of a module (from random import choice).

  2. import - Used to bring a module or part of a module into the current namespace.

  3. lambda - Used to create an anonymous function.

  4. for - Used in the list comprehension to iterate over a range.

  5. in - Used in the for loop to iterate over elements.

Files & folders#

This section reviews options for working with files and folders in Python. There are some tools typically used in such cases:

  • os: A core Python module for interacting with the operating system.

  • pathlib: A package that provides convenient path operations in Python.

  • shutil: Implements additional tools not available in the previous modules out of the box.

Find out more in the special page.


As example really typical task - list content of the /tmp folder:

import os
os.listdir("/tmp")[:5]
['dumps',
 'pyright-11804-s2fIQ36Ehj4n',
 'snap-private-tmp',
 'steam_chrome_overlay_uid1000_spid10387',
 'systemd-private-57bd5d93c4894144aa34f82104c1dc8e-fwupd.service-wLri9E']

Packages#

Packages in Python are additional code modules that extend the standard Python library. This section provides an overview of:

  • Building packages: Transforming source code into a distributable format.

  • Installing packages: Tools and methods for managing Python packages.

  • Python indexes: Repositories for storing Python packages and the process of uploading packages to them.

Find all that staff on the particular page of this site.


The packages are usually located in the lib/python<version>/site-packages directory of the Python distribution. The following cell shows the exact directory for the interpreter used to show examples.

Random entitlements from this folder will also be printed.

import os
import sys
import random
from pathlib import Path

packages_path = sys.path[-2]
print(packages_path, end="\n"*3)
for f in random.sample(os.listdir(packages_path), 10):
    print(f)
/home/fedor/.virtualenvironments/python/lib/python3.13/site-packages


async_lru
torch
referencing-0.36.2.dist-info
apscheduler
fqdn
jupyter_server_terminals-0.5.3.dist-info
tinycss2-1.4.0.dist-info
jupyter_lsp-2.2.5.dist-info
isoduration-20.11.0.dist-info
jupyter_server

The most basic tool for working with Python packages, pip, is itself a Python package. The following cell navigates to its folder and displays the contents of its __init__.py file.

print((Path(packages_path)/"pip"/"__init__.py").read_text())
from typing import List, Optional

__version__ = "25.1.1"


def main(args: Optional[List[str]] = None) -> int:
    """This is an internal API only meant for use by pip's own console scripts.

    For additional details, see https://github.com/pypa/pip/issues/7498.
    """
    from pip._internal.utils.entrypoints import _wrapper

    return _wrapper(args)

Constructs#

Python contains a set of approaches that allow you to use some special constructs in your custom way. Below is a list of things that related to the special python concepts and protocols:

Name

Description

dataclass

A decorator that generates init, repr, eq, etc., for classes with fields.

iterator

An object implementing __iter__() and __next__().

iterable

An object implementing __iter__(); can be looped over.

generator

A special iterator created with a function using yield.

coroutine

A special function using async def and await, pausable at await.

async generator

Like a generator, but supports asynchronous iteration with async for.

context manager

Implements __enter__ and __exit__; used with the with statement.

descriptor

Object defining any of __get__, __set__, __delete__; controls access.

callable

Any object implementing __call__(), i.e. can be called like a function.

function

A user-defined callable object created with def or lambda.

classmethod

A method bound to the class, not instance, via @classmethod.

staticmethod

A method that doesn’t receive implicit first argument.

property

A managed attribute using @property and optional setters/getters.

metaclass

A class of a class; controls class creation via type or custom classes.

abstract class

Class with abstract methods using abc.ABCMeta and @abstractmethod.

namedtuple

A tuple subclass with named fields, created via collections.namedtuple.

enum

A set of symbolic names bound to unique constant values.

buffer

Object exposing the buffer protocol, used for memory sharing (e.g. bytes).

slice

Built-in object representing a slice of a sequence.

mapping

Object supporting __getitem__, __setitem__, etc. (e.g. dict-like).

sequence

Ordered collection supporting indexing and slicing (e.g. lists, tuples).

hashable

Object with a __hash__() method; usable as a dictionary key or set item.

comparable

Object supporting rich comparison methods (__eq__, __lt__, etc).

file-like

Object implementing read, write, etc.; used in file APIs.

awaitable

Object that can be awaited (e.g. coroutine, object with __await__()).

contextvars.ContextVar

Represents a context-local variable, useful in async code.

Check details in Constructs page.