### Manage multiple patches in setUp and tearDown Source: https://docs.python.org/3.14/library/unittest.mock.html This example demonstrates a common pattern for managing multiple patches within a `unittest.TestCase` using `setUp` and `tearDown` methods to start and stop patchers. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` -------------------------------- ### setUpClass and tearDownClass Example Source: https://docs.python.org/3.14/library/unittest.html Example implementation of class-level setup and teardown methods using `@classmethod`. These methods are called once per class. ```python import unittest class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls._connection = createExpensiveConnectionObject() @classmethod def tearDownClass(cls): cls._connection.destroy() ``` -------------------------------- ### Process Lifecycle Example Source: https://docs.python.org/3.14/library/multiprocessing.html Example demonstrating the usage of Process creation, starting, termination, and checking the exit code. ```APIDOC ## Process Lifecycle Example ```python >>> import multiprocessing, time, signal >>> mp_context = multiprocessing.get_context('spawn') >>> p = mp_context.Process(target=time.sleep, args=(1000,)) >>> print(p, p.is_alive()) <...Process ... initial> False >>> p.start() >>> print(p, p.is_alive()) <...Process ... started> True >>> p.terminate() >>> time.sleep(0.1) >>> print(p, p.is_alive()) <...Process ... stopped exitcode=-SIGTERM> False >>> p.exitcode == -signal.SIGTERM True ``` ``` -------------------------------- ### Basic Logging Example Source: https://docs.python.org/3.14/howto/logging-cookbook.html Demonstrates basic logging with different severity levels. No special setup is required. ```python import logging logger1 = logging.getLogger('myapp.area1') logger2 = logging.getLogger('myapp.area2') logger1.debug('Quick zephyrs blow, vexing daft Jim.') logger1.info('How quickly daft jumping zebras vex.') logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') ``` -------------------------------- ### Server Setup for MultiCall Example Source: https://docs.python.org/3.14/library/xmlrpc.client.html Basic server setup to demonstrate the `MultiCall` functionality. It registers several simple arithmetic functions that can be called remotely. ```python from xmlrpc.server import SimpleXMLRPCServer def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x // y ``` -------------------------------- ### Distutils Setup with Classifiers Source: https://docs.python.org/3.14/whatsnew/2.3.html An example of a `setup.py` file demonstrating the use of the `classifiers` keyword argument for package metadata, compatible with older Distutils versions. ```python from distutils import core kw = {"name": "Quixote", "version": "0.5.1", "description": "A highly Pythonic Web application framework", # ... } if (hasattr(core, 'setup_keywords') and 'classifiers' in core.setup_keywords): kw['classifiers'] = \ ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers'], core.setup(**kw) ``` -------------------------------- ### Usage Example for Get HTTP Headers Source: https://docs.python.org/3.14/library/asyncio-stream.html Demonstrates how to run the HTTP header retrieval script from the command line. ```bash python example.py http://example.com/path/page.html ``` ```bash python example.py https://example.com/path/page.html ``` -------------------------------- ### Process Lifecycle Example Source: https://docs.python.org/3.14/library/multiprocessing.html Demonstrates starting, checking liveness, terminating, and verifying the exit code of a Process. Note that the Process context is explicitly set to 'spawn'. ```python import multiprocessing, time, signal mp_context = multiprocessing.get_context('spawn') p = mp_context.Process(target=time.sleep, args=(1000,)) print(p, p.is_alive()) p.start() print(p, p.is_alive()) p.terminate() time.sleep(0.1) print(p, p.is_alive()) p.exitcode == -signal.SIGTERM True ``` -------------------------------- ### setup.py for C extension modules Source: https://docs.python.org/3.14/whatsnew/2.0.html This setup.py example demonstrates how to define and build C extension modules, including specifying include directories and source files. It requires 'distutils.core' and 'Extension'. ```python from distutils.core import setup, Extension expat_extension = Extension('xml.parsers.pyexpat', define_macros = [('XML_NS', None)], include_dirs = [ 'extensions/expat/xmltok', 'extensions/expat/xmlparse' ], sources = [ 'extensions/pyexpat.c', 'extensions/expat/xmltok/xmltok.c', 'extensions/expat/xmltok/xmlrole.c', ] ) setup (name = "PyXML", version = "0.5.4", ext_modules =[ expat_extension ] ) ``` -------------------------------- ### Install a package and activate virtual environment Source: https://docs.python.org/3.14/library/importlib.metadata.html Demonstrates how to create a virtual environment, activate it, and install a package using pip. ```bash $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### Getting a String Input with getstr() Source: https://docs.python.org/3.14/howto/curses.html This example demonstrates how to enable echoing of characters and then retrieve a string input of up to 15 characters from the user, starting at the top-left corner of the screen. ```python curses.echo() # Enable echoing of characters # Get a 15-character string, with the cursor on the top line s = stdscr.getstr(0,0, 15) ``` -------------------------------- ### GET Request Example Source: https://docs.python.org/3.14/library/http.client.html Example of making a GET request and reading the response. ```APIDOC ## GET / ### Description Retrieves a resource. ### Method GET ### Endpoint / ### Request Example ```python import http.client conn = http.client.HTTPSConnection("www.python.org") conn.request("GET", "/") r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() ``` ### Response #### Success Response (200) - **status** (int) - HTTP status code. - **reason** (str) - HTTP reason phrase. - **data** (bytes) - Response body content. ``` -------------------------------- ### turtle.setup() Source: https://docs.python.org/3.14/library/turtle.html Sets the size and position of the main window. ```APIDOC ## setup(_width =_CFG['width']_, _height =_CFG['height']_, _startx =_CFG['leftright']_, _starty =_CFG['topbottom']_) ### Description Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a `turtle.cfg` file. ### Parameters #### Path Parameters - **width** (integer or float) - Optional - if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen - **height** (integer or float) - Optional - if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen - **startx** (integer or None) - Optional - if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if `None`, center window horizontally - **starty** (integer or None) - Optional - if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if `None`, center window vertically ### Request Example ``` >>> screen.setup (width=200, height=200, startx=0, starty=0) >>> # sets window to 200x200 pixels, in upper left of screen >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) >>> # sets window to 75% of screen by 50% of screen and centers ``` ``` -------------------------------- ### Get Start Attribute Source: https://docs.python.org/3.14/c-api/exceptions.html Retrieves the start attribute from a Unicode exception object. The start value is clipped to the valid range of the object's indices. ```APIDOC ## PyUnicodeDecodeError_GetStart / PyUnicodeEncodeError_GetStart / PyUnicodeTranslateError_GetStart ### Description Get the _start_ attribute of the given exception object and place it into _*start_. _start_ must not be `NULL`. Return `0` on success, `-1` on failure. If the `UnicodeError.object` is an empty sequence, the resulting _start_ is `0`. Otherwise, it is clipped to `[0, len(object) - 1]`. ### Signature ```c int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) ``` ### Return Value `0` on success, `-1` on failure. ### See Also `UnicodeError.start` ``` -------------------------------- ### count() Example Source: https://docs.python.org/3.14/library/itertools.html Creates an iterator that returns evenly spaced values starting with 'start' and incrementing by 'step'. ```python from itertools import count # Example usage: take the first 5 elements list(count(10))[:5] ``` -------------------------------- ### Basic Example Source: https://docs.python.org/3.14/library/zipapp.html Example of creating an executable archive from a directory and running it. ```APIDOC ## Basic Example This example shows how the Command-Line Interface can be used to create an executable archive from a directory containing Python code. When run, the archive will execute the `main` function from the module `myapp` in the archive. ```bash $ python -m zipapp myapp -m "myapp:main" $ python myapp.pyz ``` ``` -------------------------------- ### test.support.import_helper.modules_setup() Source: https://docs.python.org/3.14/library/test.html Returns a copy of `sys.modules`. ```APIDOC ## modules_setup() ### Description Return a copy of `sys.modules`. ### Response #### Success Response (200) - **sys.modules** (dict) - A dictionary representing the current state of loaded modules. ``` -------------------------------- ### Install Specific Python Version on OpenBSD Source: https://docs.python.org/3.14/using/unix.html Example command to install a specific version (2.5.1) of Python for i386 architecture on OpenBSD. ```bash pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### setup_scripts Source: https://docs.python.org/3.14/library/venv.html Installs activation scripts appropriate to the platform into the virtual environment. ```APIDOC ## setup_scripts(_context_) ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Parameters * `_context_` - The context object for the virtual environment. ``` -------------------------------- ### Basic Process Creation and Execution Source: https://docs.python.org/3.14/library/multiprocessing.html Demonstrates how to create a Process object, start it, and wait for it to complete using `start()` and `join()`. ```python from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=("bob",)) p.start() p.join() ``` -------------------------------- ### Main Function for Multiprocessing Logging Example Source: https://docs.python.org/3.14/howto/logging-cookbook.html Sets up and manages worker and listener processes for a multiprocessing logging example. It initializes logging, starts worker processes, starts a listener process, waits for workers to complete, signals the listener to stop, and then joins all processes. ```python if __name__ == '__main__': main() ``` -------------------------------- ### Get Multiprocessing Context with Specific Start Method Source: https://docs.python.org/3.14/library/multiprocessing.html Obtain a context object using `get_context()` to manage multiprocessing with a specific start method. This allows for multiple start methods within the same program. ```python import multiprocessing as mp def foo(q): q.put('hello') if __name__ == '__main__': ctx = mp.get_context('spawn') q = ctx.Queue() p = ctx.Process(target=foo, args=(q,)) p.start() print(q.get()) p.join() ``` -------------------------------- ### Get Root from Windows Path Source: https://docs.python.org/3.14/library/pathlib.html Illustrates how to get the root component of a Windows path. An empty string is returned if the path does not start with a root. ```python >>> PureWindowsPath('c:/Program Files/').root '\' >>> PureWindowsPath('c:Program Files/').root '' >>> PurePosixPath('/etc').root '/' ``` -------------------------------- ### Install Packages from Requirements File Source: https://docs.python.org/3.14/tutorial/venv.html Install all packages listed in a 'requirements.txt' file. This is the standard way to set up an application's dependencies. ```bash (tutorial-env) $ python -m pip install -r requirements.txt ``` -------------------------------- ### Get Distribution Package Version Source: https://docs.python.org/3.14/library/importlib.metadata.html Use the version() function to retrieve the installed version of a distribution package. Raises PackageNotFoundError if the package is not installed. ```python >>> version('wheel') '0.32.3' ``` -------------------------------- ### Handler Configuration Example Source: https://docs.python.org/3.14/library/logging.config.html Demonstrates the configuration of console and file handlers using a dictionary schema. Shows how to specify class, formatter, level, filters, and handler-specific arguments. ```yaml handlers: console: class : logging.StreamHandler formatter: brief level : INFO filters: [allow_foo] stream : ext://sys.stdout file: class : logging.handlers.RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3 ``` -------------------------------- ### Get Distribution Package Requirements Source: https://docs.python.org/3.14/library/importlib.metadata.html Use the requires() function to get the declared dependency specifiers for a distribution package. Raises PackageNotFoundError if the package is not installed. ```python >>> requires('wheel') ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"] ``` -------------------------------- ### Setup Script for C Extension Source: https://docs.python.org/3.14/extending/newtypes_tutorial.html A `setup.py` script that configures the build process for a C extension module named 'custom' located in 'custom.c'. ```python from setuptools import Extension, setup setup(ext_modules=[Extension("custom", ["custom.c"])])) ``` -------------------------------- ### SimpleXMLRPCServer Example Source: https://docs.python.org/3.14/library/xmlrpc.server.html A complete example demonstrating how to set up and run a SimpleXMLRPCServer, register functions and instances, and handle requests. ```APIDOC ## SimpleXMLRPCServer Example ### Server Code ```python from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) # Create server with SimpleXMLRPCServer(('localhost', 8000), requestHandler=RequestHandler) as server: server.register_introspection_functions() # Register pow() function; this will use the value of # pow.__name__ as the name, which is just 'pow'. server.register_function(pow) # Register a function under a different name def adder_function(x, y): return x + y server.register_function(adder_function, 'add') # Register an instance; all the methods of the instance are # published as XML-RPC methods (in this case, just 'mul'). class MyFuncs: def mul(self, x, y): return x * y server.register_instance(MyFuncs()) # Run the server's main loop server.serve_forever() ``` ### Client Code Example ```python import xmlrpc.client s = xmlrpc.client.ServerProxy('http://localhost:8000') print(s.pow(2,3)) # Returns 2**3 = 8 print(s.add(2,3)) # Returns 5 print(s.mul(5,2)) # Returns 5*2 = 10 ``` ``` -------------------------------- ### Match 'From' at the Start of a Line Source: https://docs.python.org/3.14/howto/regex.html Use the '^' metacharacter to anchor a pattern to the beginning of a line. This example shows matching 'From' only when it appears at the start of the string. ```python >>> print(re.search('^From', 'From Here to Eternity')) >>> print(re.search('^From', 'Reciting From Memory')) None ``` -------------------------------- ### Print Program Version Source: https://docs.python.org/3.14/library/optparse.html Example of how the --version option is invoked from the command line to display the program's version string. ```bash $ /usr/bin/foo --version foo 1.0 ``` -------------------------------- ### Starting the Python Interpreter Source: https://docs.python.org/3.14/faq/windows.html Enter this command in the Windows command prompt to start the Python interpreter in interactive mode. Ensure Python is installed and accessible in your PATH. ```bash C:\Users\YourName> py ``` -------------------------------- ### Listener and Client Example Source: https://docs.python.org/3.14/library/multiprocessing.html Demonstrates how to create a server listener that accepts connections and sends data, and a client that connects to the listener and receives data. ```APIDOC ## Listener Example ### Description Creates a listener on a specified address with authentication and accepts incoming connections. It then sends various data types to the connected client. ### Method `Listener(address, authkey)` ### Endpoint N/A (This is an SDK example) ### Parameters - **address** (tuple) - The address to bind the listener to (e.g., ('localhost', 6000)). - **authkey** (bytes) - The authentication key for the connection. ### Request Example ```python from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) with Listener(address, authkey=b'secret password') as listener: with listener.accept() as conn: print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') conn.send_bytes(array('i', [42, 1729])) ``` ## Client Example ### Description Connects to a server listener using a specified address and authentication key. It then receives data sent by the server. ### Method `Client(address, authkey)` ### Endpoint N/A (This is an SDK example) ### Parameters - **address** (tuple) - The address of the server to connect to (e.g., ('localhost', 6000)). - **authkey** (bytes) - The authentication key for the connection. ### Request Example ```python from multiprocessing.connection import Client from array import array address = ('localhost', 6000) with Client(address, authkey=b'secret password') as conn: print(conn.recv()) print(conn.recv_bytes()) arr = array('i', [0, 0, 0, 0, 0]) print(conn.recv_bytes_into(arr)) print(arr) ``` ``` -------------------------------- ### Example HTML Parser Application Source: https://docs.python.org/3.14/library/html.parser.html This example demonstrates how to subclass HTMLParser to create a custom parser that prints encountered start tags, end tags, and data. ```APIDOC from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Encountered a start tag:", tag) def handle_endtag(self, tag): print("Encountered an end tag :", tag) def handle_data(self, data): print("Encountered some data :", data) parser = MyHTMLParser() parser.feed('Test'\n '

Parse me!

') ``` -------------------------------- ### Example Command Line for 'extend' Action Source: https://docs.python.org/3.14/library/optparse.html Demonstrates how multiple values can be provided for an 'extend' action, either through repeated options or a comma-delimited string. ```bash --names=foo,bar --names blah --names ding,dong ``` -------------------------------- ### Get SQLite Connection Runtime Limit Source: https://docs.python.org/3.14/library/sqlite3.html Queries a specific runtime limit for an SQLite connection. This example shows how to get the maximum length of an SQL statement. ```python con.getlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH) ``` -------------------------------- ### Advanced Python Initialization with Configuration Source: https://docs.python.org/3.14/c-api/init_config.html Provides a more comprehensive example of initializing Python, including reading the configuration, modifying search paths, overriding the executable, and handling errors. ```APIDOC ## Py_InitializeFromConfig with Advanced Configuration ### Description Initializes the Python interpreter with a customized configuration, demonstrating how to read, modify, and apply settings like program name, module search paths, and executable path. ### Method `PyStatus Py_InitializeFromConfig(PyConfig *config)` ### Parameters * **config** (`PyConfig *`) - A pointer to a `PyConfig` struct populated with desired configuration settings. ### Request Example ```c PyStatus init_python(const char *program_name) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); /* Set the program name before reading the configuration (decode byte string from the locale encoding). Implicitly preinitialize Python. */ status = PyConfig_SetBytesString(&config, &config.program_name, program_name); if (PyStatus_Exception(status)) { goto done; } /* Read all configuration at once */ status = PyConfig_Read(&config); if (PyStatus_Exception(status)) { goto done; } /* Specify sys.path explicitly */ /* If you want to modify the default set of paths, finish initialization first and then use PySys_GetObject("path") */ config.module_search_paths_set = 1; status = PyWideStringList_Append(&config.module_search_paths, L"/path/to/stdlib"); if (PyStatus_Exception(status)) { goto done; } status = PyWideStringList_Append(&config.module_search_paths, L"/path/to/more/modules"); if (PyStatus_Exception(status)) { goto done; } /* Override executable computed by PyConfig_Read() */ status = PyConfig_SetString(&config, &config.executable, L"/path/to/my_executable"); if (PyStatus_Exception(status)) { goto done; } status = Py_InitializeFromConfig(&config); done: PyConfig_Clear(&config); return status; } ``` ### Response * **PyStatus**: Returns a `PyStatus` indicating success or failure. Errors should be handled using `PyStatus_Exception()` and `Py_ExitStatusException()`. ``` -------------------------------- ### patch methods: start and stop Source: https://docs.python.org/3.14/library/unittest.mock.html All patchers have `start()` and `stop()` methods. These make it simpler to do patching in `setUp` methods or where you want to do multiple patches without nesting decorators or with statements. ```APIDOC ## patch methods: start and stop ### Description All the patchers have `start()` and `stop()` methods. These make it simpler to do patching in `setUp` methods or where you want to do multiple patches without nesting decorators or with statements. To use them call `patch()`, `patch.object()` or `patch.dict()` as normal and keep a reference to the returned `patcher` object. You can then call `start()` to put the patch in place and `stop()` to undo it. If you are using `patch()` to create a mock for you then it will be returned by the call to `patcher.start`. ### Usage ```python >>> patcher = patch('package.module.ClassName') >>> from package import module >>> original = module.ClassName >>> new_mock = patcher.start() >>> assert module.ClassName is not original >>> assert module.ClassName is new_mock >>> patcher.stop() >>> assert module.ClassName is original >>> assert module.ClassName is not new_mock ``` A typical use case for this might be for doing multiple patches in the `setUp` method of a `TestCase`: ### setUp Example ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` **Caution** If you use this technique you must ensure that the patching is “undone” by calling `stop`. This can be fiddlier than you might think, because if an exception is raised in the `setUp` then `tearDown` is not called. `unittest.TestCase.addCleanup()` makes this easier: ### addCleanup Example ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... patcher = patch('package.module.Class') ... self.MockClass = patcher.start() ... self.addCleanup(patcher.stop) ... ... def test_something(self): ... assert package.module.Class is self.MockClass ... ``` As an added bonus you no longer need to keep a reference to the `patcher` object. It is also possible to stop all patches which have been started by using `patch.stopall()`. ``` -------------------------------- ### Install Python from Source Safely Source: https://docs.python.org/3.14/using/unix.html Use 'make altinstall' instead of 'make install' to avoid overwriting the default 'python3' binary when installing from source. ```bash make altinstall ``` -------------------------------- ### Get Distribution Version Source: https://docs.python.org/3.14/library/importlib.metadata.html Access the version of an installed distribution package through its Distribution instance. ```python dist.version ``` -------------------------------- ### os.startfile Source: https://docs.python.org/3.14/library/os.html Start a file with its associated application. ```APIDOC ## os.startfile ### Description Start a file with its associated application. ### Parameters - _path_ (str) - The path to the file to start. - _operation_ (str, optional) - The operation to perform on the file (e.g., 'open', 'print'). - _arguments_ (str, optional) - Additional arguments for the operation. - _cwd_ (str, optional) - The current working directory for the operation. - _show_cmd_ (int, optional) - Specifies how the application window should be shown. ``` -------------------------------- ### Get Distribution Version Source: https://docs.python.org/3.14/library/importlib.metadata.html Retrieves the version string for a specified installed distribution package. ```APIDOC ## version ### Description Retrieves the version string for a specified installed distribution package. ### Signature `version(name: str) -> str` ### Parameters * **name** (str) - The name of the distribution package. ### Returns (str) - The version string of the distribution package. ### Example ```python from importlib.metadata import version version('wheel') ``` ``` -------------------------------- ### Managing patches with setUp and tearDown Source: https://docs.python.org/3.14/library/unittest.mock-examples.html Use `patcher.start()` in `setUp` and `patcher.stop()` in `tearDown` to manage patches. Ensure `stop()` is called to undo patching, even if exceptions occur. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher = patch('mymodule.foo') ... self.mock_foo = self.patcher.start() ... ... def test_foo(self): ... self.assertIs(mymodule.foo, self.mock_foo) ... ... def tearDown(self): ... self.patcher.stop() ... >>> MyTest('test_foo').run() ``` -------------------------------- ### Get Distribution Metadata Source: https://docs.python.org/3.14/library/importlib.metadata.html Retrieves a list of metadata keys for a specified installed distribution package. ```APIDOC ## metadata ### Description Retrieves a list of metadata keys for a specified installed distribution package. ### Signature `metadata(name: str) -> list[str]` ### Parameters * **name** (str) - The name of the distribution package. ### Returns (list[str]) - A list of metadata keys for the distribution package. ### Example ```python from importlib.metadata import metadata list(metadata('wheel')) ``` ``` -------------------------------- ### Extend venv.EnvBuilder to install setuptools and pip Source: https://docs.python.org/3.14/library/venv.html Subclass `venv.EnvBuilder` to add custom logic to the virtual environment creation process. Override `post_setup` to install packages like setuptools and pip after the environment is initially set up. This example includes options to disable installation of distribution tools. ```python import os import os.path from subprocess import Popen, PIPE import sys from threading import Thread from urllib.parse import urlsplit from urllib.request import urlretrieve import venv class ExtendedEnvBuilder(venv.EnvBuilder): """ This builder installs setuptools and pip so that you can pip or easy_install other packages into the created virtual environment. :param nodist: If true, setuptools and pip are not installed into the created virtual environment. :param nopip: If true, pip is not installed into the virtual environment. :param progress: If setuptools or pip are installed, the progress of the installation can be monitored by passing a progress callable. If specified, it is called with two arguments: a string indicating some progress, and a context indicating where the string is coming from. The context argument can have one of three values: 'main', indicating that it is called from virtualize() itself, and 'stdout' and 'stderr', which are obtained by reading lines from the output streams of a subprocess which is used to install the app. If a callable is not specified, default progress information is output to sys.stderr. """ def __init__(self, *args, **kwargs): self.nodist = kwargs.pop('nodist', False) self.nopip = kwargs.pop('nopip', False) self.progress = kwargs.pop('progress', None) self.verbose = kwargs.pop('verbose', False) super().__init__(*args, **kwargs) def post_setup(self, context): """ Set up any packages which need to be pre-installed into the virtual environment being created. :param context: The information for the virtual environment creation request being processed. """ os.environ['VIRTUAL_ENV'] = context.env_dir if not self.nodist: self.install_setuptools(context) # Can't install pip without setuptools if not self.nopip and not self.nodist: self.install_pip(context) def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. """ progress = self.progress while True: s = stream.readline() if not s: break if progress is not None: progress(s, context) else: if not self.verbose: sys.stderr.write('.') else: sys.stderr.write(s.decode('utf-8')) sys.stderr.flush() stream.close() def install_script(self, context, name, url): _, _, path, _, _ = urlsplit(url) fn = os.path.split(path)[-1] binpath = context.bin_path distpath = os.path.join(binpath, fn) # Download script into the virtual environment's binaries folder urlretrieve(url, distpath) progress = self.progress if self.verbose: term = '\n' else: term = '' if progress is not None: progress('Installing %s ...%s' % (name, term), 'main') else: sys.stderr.write('Installing %s ...%s' % (name, term)) sys.stderr.flush() # Install in the virtual environment args = [context.env_exe, fn] p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) t1 = Thread(target=self.reader, args=(p.stdout, 'stdout')) t1.start() t2 = Thread(target=self.reader, args=(p.stderr, 'stderr')) t2.start() p.wait() t1.join() t2.join() if progress is not None: progress('done.', 'main') else: sys.stderr.write('done.\n') # Clean up - no longer needed os.unlink(distpath) def install_setuptools(self, context): """ Install setuptools in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = "https://bootstrap.pypa.io/ez_setup.py" self.install_script(context, 'setuptools', url) # clear up the setuptools archive which gets downloaded pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') files = filter(pred, os.listdir(context.bin_path)) for f in files: pass # This part of the code is incomplete in the source ``` -------------------------------- ### Create a Listener and Accept Connection Source: https://docs.python.org/3.14/library/multiprocessing.html Sets up a server listener with authentication and accepts an incoming client connection. Data is then sent to the client. ```python from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) # family is deduced to be 'AF_INET' with Listener(address, authkey=b'secret password') as listener: with listener.accept() as conn: print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') conn.send_bytes(array('i', [42, 1729])) ``` -------------------------------- ### Start and stop patches manually Source: https://docs.python.org/3.14/library/unittest.mock.html Patcher objects returned by `patch`, `patch.object`, or `patch.dict` have `start()` and `stop()` methods. This allows for manual control over patching, useful in `setUp` methods or when avoiding nested decorators. ```python >>> patcher = patch('package.module.ClassName') >>> from package import module >>> original = module.ClassName >>> new_mock = patcher.start() >>> assert module.ClassName is not original >>> assert module.ClassName is new_mock >>> patcher.stop() >>> assert module.ClassName is original >>> assert module.ClassName is not new_mock ``` -------------------------------- ### Initialize Python with Custom Configuration Source: https://docs.python.org/3.14/c-api/init_config.html Example of initializing Python with custom configuration, enabling Python Development Mode. Handles memory allocation failures and initialization errors. ```c int init_python(void) { PyInitConfig *config = PyInitConfig_Create(); if (config == NULL) { printf("PYTHON INIT ERROR: memory allocation failed\n"); return -1; } // Enable the Python Development Mode if (PyInitConfig_SetInt(config, "dev_mode", 1) < 0) { goto error; } // Initialize Python with the configuration if (Py_InitializeFromInitConfig(config) < 0) { goto error; } PyInitConfig_Free(config); return 0; error: { // Display the error message. // // This uncommon braces style is used, because you cannot make // goto targets point to variable declarations. const char *err_msg; (void)PyInitConfig_GetError(config, &err_msg); printf("PYTHON INIT ERROR: %s\n", err_msg); PyInitConfig_Free(config); return -1; } } ``` -------------------------------- ### Instantiate CustomAdapter Source: https://docs.python.org/3.14/howto/logging-cookbook.html Example of how to instantiate the CustomAdapter with a logger and contextual information. ```python logger = logging.getLogger(__name__) adapter = CustomAdapter(logger, {'connid': some_conn_id}) ``` -------------------------------- ### readline.set_completer_delims, readline.get_completer_delims Source: https://docs.python.org/3.14/library/readline.html Set or get the word delimiters used for completion, which determine the start of a word for completion. ```APIDOC ## readline.set_completer_delims(string) ### Description Set the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the `rl_completer_word_break_characters` variable in the underlying library. ## readline.get_completer_delims() ### Description Get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the `rl_completer_word_break_characters` variable in the underlying library. ``` -------------------------------- ### Get Distribution Instance Source: https://docs.python.org/3.14/library/importlib.metadata.html Retrieve a Distribution instance for a named package. Raises PackageNotFoundError if the package is not installed. ```python from importlib.metadata import distribution dist = distribution('wheel') type(dist) ``` -------------------------------- ### Start HTTP Server and Open Browser Source: https://docs.python.org/3.14/library/pydoc.html Start the HTTP documentation server and automatically open a web browser to the module index page. ```bash python -m pydoc -b ``` -------------------------------- ### Example Usage Source: https://docs.python.org/3.14/library/sched.html This example demonstrates how to use the `sched` module to schedule and execute events. It shows how to create a scheduler instance, define event functions, and schedule them using `enter` and `enterabs` with different priorities and arguments. ```APIDOC ## Example ```python import sched, time s = sched.scheduler(time.time, time.sleep) def print_time(a='default'): print("From print_time", time.time(), a) def print_some_times(): print(time.time()) # Schedule an event to run after 10 seconds with priority 1 s.enter(10, 1, print_time) # Schedule an event to run after 5 seconds with priority 2 s.enter(5, 2, print_time, argument=('positional',)) # Schedule an event to run after 5 seconds with priority 1 s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) # Schedule an event to run at a specific absolute time with priority 10 s.enterabs(1_650_000_000, 10, print_time, argument=("first enterabs",)) # Schedule another event at the same absolute time but with priority 5 s.enterabs(1_650_000_000, 5, print_time, argument=("second enterabs",)) # Run all scheduled events s.run() print(time.time()) print_some_times() ``` ``` -------------------------------- ### Get package version using `importlib.metadata` Source: https://docs.python.org/3.14/library/importlib.metadata.html Shows how to import the `version` function and retrieve the version of an installed package. ```python >>> from importlib.metadata import version >>> version('wheel') '0.32.3' ``` -------------------------------- ### Implementing setUp and tearDown for Test Fixtures Source: https://docs.python.org/3.14/library/unittest.html Use setUp() to prepare test fixtures before each test method and tearDown() to clean up after each test method. These methods are automatically called by the framework. ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def test_default_widget_size(self): self.assertEqual(self.widget.size(), (50,50), 'incorrect default size') def test_widget_resize(self): self.widget.resize(100,150) self.assertEqual(self.widget.size(), (100,150), 'wrong size after resize') ``` ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() ``` -------------------------------- ### Package Metadata with Distutils setup() Source: https://docs.python.org/3.14/whatsnew/2.5.html Configure package metadata in setup.py using new keyword parameters like requires, obsoletes, and download_url for better dependency management and distribution. ```python VERSION = '1.0' setup(name='PyPackage', version=VERSION, requires=['numarray', 'zlib (>=1.1.4)'], obsoletes=['OldPackage'] download_url=('http://www.example.com/pypackage/dist/pkg-%s' % VERSION), ) ``` -------------------------------- ### Get Arena Allocator Source: https://docs.python.org/3.14/c-api/memory.html Retrieves the current arena allocator configuration. This function is available starting from Python 3.4. ```c void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator); ``` -------------------------------- ### Example: Get Ciphers After Setting Source: https://docs.python.org/3.14/library/ssl.html Demonstrates setting ciphers using set_ciphers() and then retrieving the list of enabled ciphers with get_ciphers(). ```python >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') >>> ctx.get_ciphers() [{'aead': True, 'alg_bits': 256, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' \ 'Enc=AESGCM(256) Mac=AEAD', 'digest': None, 'id': 50380848, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1.2', 'strength_bits': 256, 'symmetric': 'aes-256-gcm'}, {'aead': True, 'alg_bits': 128, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' \ 'Enc=AESGCM(128) Mac=AEAD', 'digest': None, 'id': 50380847, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1.2', 'strength_bits': 128, 'symmetric': 'aes-128-gcm'}] ``` -------------------------------- ### Display Help Information Source: https://docs.python.org/3.14/using/cmdline.html Various options are available to display help messages. Use -h or --help for a short description of all command-line options. For more specific help, use --help-env for environment variables, --help-xoptions for implementation-specific options, and --help-all for complete usage information. ```bash -? ``` ```bash -h ``` ```bash --help ``` ```bash --help-env ``` ```bash --help-xoptions ``` ```bash --help-all ``` -------------------------------- ### sys.base_exec_prefix Source: https://docs.python.org/3.14/library/sys.html Equivalent to `exec_prefix`, but referring to the base Python installation. When running under Virtual Environments, `exec_prefix` gets overwritten, but `base_exec_prefix` does not. ```APIDOC ## sys.base_exec_prefix ### Description Equivalent to `exec_prefix`, but referring to the base Python installation. When running under Virtual Environments, `exec_prefix` gets overwritten to the virtual environment prefix. `base_exec_prefix`, conversely, does not change, and always points to the base Python installation. Refer to Virtual Environments for more information. ### Changes - **Version 3.3**: Added. ``` -------------------------------- ### Setting and Getting the First Weekday Source: https://docs.python.org/3.14/library/calendar.html You can set the weekday that starts each week (e.g., Monday or Sunday) and retrieve the current setting. ```APIDOC ## `setfirstweekday(weekday)` ### Description Sets the weekday to start each week. `0` represents Monday and `6` represents Sunday. Predefined constants like `MONDAY` and `SUNDAY` are available for convenience. ### Method `calendar.setfirstweekday(weekday)` ### Parameters - **weekday** (int) - The integer representing the day of the week (0-6) to set as the start of the week. ### Request Example ```python import calendar calendar.setfirstweekday(calendar.SUNDAY) ``` ## `firstweekday()` ### Description Returns the current setting for the weekday that starts each week. ### Method `calendar.firstweekday()` ### Response - **weekday** (int) - The integer representing the current first weekday of the week (0-6). ``` -------------------------------- ### Start HTTP Documentation Server Source: https://docs.python.org/3.14/library/pydoc.html Start an HTTP server on a specified port to browse documentation in a web browser. Port `0` selects an arbitrary unused port. ```bash python -m pydoc -p 1234 ``` -------------------------------- ### Prepare Environment for Logging Source: https://docs.python.org/3.14/howto/logging-cookbook.html A Bash script to prepare the environment for testing the logging setup. It creates necessary directories and installs dependencies. ```bash #!/bin/sh # Create directories for logs and supervisor mkdir -p run # Create a virtual environment python3 -m venv venv # Activate virtual environment and install dependencies . venv/bin/activate pip install bottle gunicorn supervisor echo "Environment prepared. Run 'bash ensure_app.sh' to start the application." ``` -------------------------------- ### Example __main__.py for a package Source: https://docs.python.org/3.14/library/__main__.html This __main__.py file is designed for a hypothetical 'bandclass' package, demonstrating how to handle command-line arguments and import modules within the package. ```python # bandclass/__main__.py import sys from .student import search_students student_name = sys.argv[1] if len(sys.argv) >= 2 else '' print(f'Found student: {search_students(student_name)}') ``` -------------------------------- ### itertools.count() Example Source: https://docs.python.org/3.14/library/itertools.html Generates an iterator that returns evenly spaced values starting from a specified number. Useful for generating sequences or adding indices. ```python def count(start=0, step=1): # count(10) → 10 11 12 13 14 ... # count(2.5, 0.5) → 2.5 3.0 3.5 ... n = start while True: yield n n += step ``` -------------------------------- ### Get distribution metadata Source: https://docs.python.org/3.14/library/importlib.metadata.html Use the `metadata()` function with a distribution name to retrieve its package metadata as a `PackageMetadata` instance. Raises `PackageNotFoundError` if the distribution is not installed. ```python >>> wheel_metadata = metadata('wheel') ```