Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Python
https://github.com/python/cpython
Admin
The Python programming language
Tokens:
5,138,940
Snippets:
44,527
Trust Score:
8.9
Update:
7 hours ago
Context
Chat
Benchmark
75.62
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Python 2.5.1 on OpenBSD i386 Source: https://github.com/python/cpython/blob/main/Doc/using/unix.rst Example command demonstrating pkg_add with an exact FTP package archive URL for the i386 architecture. ```sh pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### Run module with verbose output Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst Use the -v switch to get a detailed report of all examples tried and summaries. ```python3 python M.py -v ``` -------------------------------- ### Multiple patches in setUp and tearDown Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock.rst Start multiple patches in setUp and stop them in tearDown. This avoids nesting decorators or context managers. ```python3 >>> 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() ``` -------------------------------- ### Build C extensions using Extension and ext_modules Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.0.rst Configure C extensions using `Extension` by specifying macro definitions, include directories, and source files. Pass the configured extension instances to `setup()` via `ext_modules` for automated compilation during install. ```python3 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 ] ) ``` -------------------------------- ### Use setUp to factor out repetitive test setup Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.rst Implement setUp to run code before each test method. The framework calls setUp automatically for every test; if setUp raises an exception, the test is considered an error and the test method is not executed. ```python3 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') ``` -------------------------------- ### Install LLVM 21 on Ubuntu or Debian Source: https://github.com/python/cpython/blob/main/Tools/jit/README.md Download and run the official LLVM setup script to install LLVM 21 on Ubuntu and Debian distributions. ```sh wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 21 ``` -------------------------------- ### Build and install CPython from source Source: https://github.com/python/cpython/blob/main/Doc/using/unix.rst Executes standard Unix build commands to configure, compile, and install CPython. Note that `make altinstall` is recommended instead of `make install` to avoid overwriting or masquerading the default `python3` binary. ```sh ./configure make make install ``` -------------------------------- ### Install Python install manager from AppInstaller file Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst Download and install the latest release by passing the AppInstaller file to Add-AppxPackage. This installs using the MSIX from python.org and is recommended only when Store installation is not possible. ```powershell $> Add-AppxPackage -AppInstallerFile https://www.python.org/ftp/python/pymanager/pymanager.appinstaller ``` -------------------------------- ### setup_scripts(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst 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. ### Method setup_scripts ### Parameters - **context** (types.SimpleNamespace) - Required - The context object returned by `ensure_directories()`. ### Response None ``` -------------------------------- ### Find all adverbs and their positions with re.finditer() Source: https://github.com/python/cpython/blob/main/Doc/library/re.rst Use re.finditer() to get Match objects instead of strings, providing more information about all matches. The example prints the start and end positions of each adverb. ```python3 >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly\b", text): ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly ``` -------------------------------- ### turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom']) Source: https://github.com/python/cpython/blob/main/Doc/library/turtle.rst Sets the size and position of the main window. Default values are stored in the configuration dictionary and can be changed via a turtle.cfg file. ```APIDOC ## turtle.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. ### Method Function ### Parameters - **width** (int or float) – Optional – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen - **height** (int or float) – Optional – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen - **startx** (int 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** (int 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 ### Return Value None ``` -------------------------------- ### Doctest examples with arbitrary starting column indentation Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst The starting column of the '>>> ' prompt does not matter. As many leading whitespace characters are stripped from the expected output as appeared in the initial '>>> ' line that started the example. ```python3 >>> assert "Easy!" >>> import math >>> math.floor(1.9) 1 ``` -------------------------------- ### Complete example module with doctests for factorial() Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst A small module whose docstrings contain interactive examples for factorial(). Running it directly calls doctest.testmod() to verify all examples. ```python3 """ This is the "example" module. The example module supplies one function, factorial(). For example, >>> factorial(5) 120 """ def factorial(n): """Return the factorial of n, an exact integer >= 0. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) 265252859812191058636308480000000 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer >>> factorial(30.0) 265252859812191058636308480000000 It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large """ import math if not n >= 0: raise ValueError("n must be >= 0") if math.floor(n) != n: raise ValueError("n must be exact integer") if n+1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result if __name__ == "__main__": import doctest doctest.testmod() ``` -------------------------------- ### Install a specific runtime variant Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst Installs a specific runtime variant by including it in the tag passed to py install. For example, installs PythonTest version 3.16. ```none py install PythonTest\3.16 ``` -------------------------------- ### Complete optparse script example Source: https://github.com/python/cpython/blob/main/Doc/library/optparse.rst A full example demonstrating OptionParser initialization, option registration, argument validation, and standard execution flow. ```python from optparse import OptionParser ... def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-f", "--file", dest="filename", help="read data from FILENAME") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") ... (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") if options.verbose: print("reading %s..." % options.filename) ... if __name__ == "__main__": main() ``` -------------------------------- ### Install from an offline index with py install --source Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst Installs one or more bundled runtimes from an offline index directory by specifying the path to the index.json file. ```none $> py install --source="<PATH>\index.json" <TAG>... ``` -------------------------------- ### post_setup(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. ```APIDOC ## post_setup(context) ### Description A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. ### Method post_setup ### Parameters - **context** (types.SimpleNamespace) - Required - The context object returned by `ensure_directories()`. ### Response None ``` -------------------------------- ### Get installed package version with version() Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Retrieves the version string for an installed distribution package. Raises PackageNotFoundError if the package is not installed in the current environment. ```python >>> version('wheel') '0.32.3' ``` -------------------------------- ### Install or uninstall MSIX using Add-AppxPackage and Remove-AppxPackage Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst Programmatically install or uninstall an MSIX using only PowerShell. The example shows installing a local MSIX file and then removing the package by name. ```powershell $> Add-AppxPackage C:\Downloads\python-manager-25.0.msix ... $> Get-AppxPackage PythonSoftwareFoundation.PythonManager | Remove-AppxPackage ``` -------------------------------- ### Install runtimes with py install Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst Installs one or more runtime versions using the py install command. Supports options for source, force, update, and dry-run. The special tag 'default' selects the default runtime; ranges are not supported. ```none $> py install [-s=|--source=<URL>] [-f|--force] [-u|--update] [--dry-run] [<TAG>...] ``` -------------------------------- ### Configure setup.py to include custom2 extension module Source: https://github.com/python/cpython/blob/main/Doc/extending/newtypes_tutorial.rst Updates setuptools setup configuration to build both the original custom extension and the new custom2 extension. ```python from setuptools import Extension, setup setup(ext_modules=[ Extension("custom", ["custom.c"]), Extension("custom2", ["custom2.c"]), ]) ``` -------------------------------- ### Convert doctest examples to a script with script_from_examples() Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst Pass a string containing doctest examples to doctest.script_from_examples(); examples become regular code and surrounding text becomes comments. ```python3 import doctest print(doctest.script_from_examples(r""" Set x and y to 1 and 2. >>> x, y = 1, 2 Print their sum: >>> print(x+y) 3 """)) ``` -------------------------------- ### Install packages from requirements.txt using pip install -r Source: https://github.com/python/cpython/blob/main/Doc/tutorial/venv.rst Installs all dependencies and versions pinned in a requirements.txt file. ```console (tutorial-env) $ python -m pip install -r requirements.txt Collecting novas==3.1.1.3 (from -r requirements.txt (line 1)) ... Collecting numpy==1.9.2 (from -r requirements.txt (line 2)) ... Collecting requests==2.7.0 (from -r requirements.txt (line 3)) ... Installing collected packages: novas, numpy, requests Running setup.py install for novas Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0 ``` -------------------------------- ### PyUnicodeDecodeError_GetStart / PyUnicodeEncodeError_GetStart / PyUnicodeTranslateError_GetStart Source: https://github.com/python/cpython/blob/main/Doc/c-api/exceptions.rst Get the start attribute of the given exception object and place it into *start. These functions are part of the Stable ABI. ```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]. ### Method C API Function ### Endpoint 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) ### Parameters - **exc** (PyObject *) - Required - The exception object. - **start** (Py_ssize_t *) - Required - Pointer to store the start attribute. ### Return Value 0 on success, -1 on failure. ### Notes Part of the Stable ABI. ``` -------------------------------- ### Benchmark expressions with setup via CLI Source: https://github.com/python/cpython/blob/main/Doc/library/timeit.rst Provide a setup statement with -s that executes once before benchmarking expressions. The output displays loop count, repetition count, and the average time of the fastest repetition. ```shell-session $ python -m timeit -s "text = 'sample string'; char = 'g'" "char in text" 5000000 loops, best of 5: 0.0877 usec per loop $ python -m timeit -s "text = 'sample string'; char = 'g'" "text.find(char)" 1000000 loops, best of 5: 0.342 usec per loop ``` -------------------------------- ### logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None) Source: https://github.com/python/cpython/blob/main/Doc/library/logging.config.rst Starts up a socket server on the specified port to listen for new logging configurations. Returns a Thread instance on which you can call start() to start the server. ```APIDOC ### `logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None)` Starts up a socket server on the specified port, and listens for new configurations. #### Parameters - **port** (int, *optional*) - The port on which to listen. Defaults to `DEFAULT_LOGGING_CONFIG_PORT`. - **verify** (callable, *optional*) - A callable used to verify whether bytes received across the socket are valid and should be processed. Takes a single argument (the received bytes) and returns either the bytes to process or `None` to discard. #### Returns - **threading.Thread** - A thread instance on which `start()` can be called to begin listening, and `join()` to wait for termination. #### Security Note Because portions of the configuration are evaluated, binding without verification on multi-user systems may pose security risks. Use the `verify` parameter to validate or decrypt incoming configuration data. ``` -------------------------------- ### ThreadingMock wait_until_called example Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock.rst Demonstrates using wait_until_called to block until a ThreadingMock is called. The example starts a thread that calls the mock and waits with a timeout. ```pycon >>> mock = ThreadingMock() >>> thread = threading.Thread(target=mock) >>> thread.start() >>> mock.wait_until_called(timeout=1) >>> thread.join() ``` -------------------------------- ### Create a virtual environment and install a package Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Sets up an isolated virtual environment and installs the target package using pip. ```shell-session $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### AsyncMock await_args_list example Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock.rst Shows that await_args_list contains all awaits made to an AsyncMock in sequence. The example starts with an empty list and appends each call. ```pycon >>> mock = AsyncMock() >>> async def main(*args): ... await mock(*args) ... >>> mock.await_args_list [] >>> asyncio.run(main('foo')) >>> mock.await_args_list [call('foo')] >>> asyncio.run(main('bar')) >>> mock.await_args_list [call('foo'), call('bar')] ``` -------------------------------- ### Benchmark expressions with setup using timeit.timeit() Source: https://github.com/python/cpython/blob/main/Doc/library/timeit.rst Use the timeit() function directly in Python, supplying the setup keyword argument for statements executed once before timing. ```python3 >>> import timeit >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"') 0.41440500499993504 >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"') 1.7246671520006203 ``` -------------------------------- ### Install python.org package via command line with installer and choicechanges.plist Source: https://github.com/python/cpython/blob/main/Doc/using/mac.rst Use the macOS installer utility to install a python.org package non-interactively, deselecting the free-threaded interpreter. Requires sudo and the installer command. The example uses release 3.16.0b2 and creates a choicechanges.plist to disable the PythonTFramework-3.16 package. ```shell RELEASE="python-3.16.0b2-macos11.pkg" # download installer pkg curl -O https://www.python.org/ftp/python/3.16.0/${RELEASE} # create installer choicechanges to customize the install: # disable the PythonTFramework-3.16 package # while accepting the other defaults (install all other packages) cat > ./choicechanges.plist <<EOF <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <dict> <key>attributeSetting</key> <integer>0</integer> <key>choiceAttribute</key> <string>selected</string> <key>choiceIdentifier</key> <string>org.python.Python.PythonTFramework-3.16</string> </dict> </array> </plist> EOF sudo installer -pkg ./${RELEASE} -applyChoiceChangesXML ./choicechanges.plist -target / ``` -------------------------------- ### Basic OptionParser script setup Source: https://github.com/python/cpython/blob/main/Doc/library/optparse.rst Create an OptionParser instance, declare options with add_option, and parse command-line arguments using parse_args(). Populates options and positional args from user input. ```python3 from optparse import OptionParser ... parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() ``` -------------------------------- ### ,Run simple_logging_config.py and view console output Source: https://github.com/python/cpython/blob/main/Doc/howto/logging.rst ,Shows the command to run the fileConfig-based logging example and the resulting formatted log lines. The output is nearly identical to the non-config-file example, using the simpleExample logger name. ```,shell-session ,$ python simple_logging_config.py 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message ``` -------------------------------- ### ThreadingMock wait_until_any_call_with example Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock.rst Shows how to use wait_until_any_call_with to wait until a ThreadingMock is called with specific arguments. The example starts a thread that calls the mock with arguments and waits for that call. ```pycon >>> mock = ThreadingMock() >>> thread = threading.Thread(target=mock, args=("arg1", "arg2",), kwargs={"arg": "thing"}) >>> thread.start() >>> mock.wait_until_any_call_with("arg1", "arg2", arg="thing") >>> thread.join() ``` -------------------------------- ### Create ranges with list(range()) examples Source: https://github.com/python/cpython/blob/main/Doc/builtins/stdtypes.rst Shows how start, stop, and step arguments determine the contents of a range. Empty ranges result when the start value does not satisfy the step constraint. ```python3 >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(0, -10, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> list(range(0)) [] >>> list(range(1, 0)) [] ``` -------------------------------- ### Test free-threaded and traditional Python interpreters after default install Source: https://github.com/python/cpython/blob/main/Doc/using/mac.rst After a default install, verify that both the free-threaded and traditional interpreters are available. The example checks /usr/local/bin/python3.16t and /usr/local/bin/python3.16, and also tests without the prefix if /usr/local/bin is on $PATH. ```shell $ # test that the free-threaded interpreter was installed if the Unix Command Tools package was enabled $ /usr/local/bin/python3.16t -VV Python 3.16.0b2 free-threading build (v3.16.0b2:3a83b172af, Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)] $ # and the traditional interpreter $ /usr/local/bin/python3.16 -VV Python 3.16.0b2 (v3.16.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)] $ # test that they are also available without the prefix if /usr/local/bin is on $PATH $ python3.16t -VV Python 3.16.0b2 free-threading build (v3.16.0b2:3a83b172af, Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)] $ python3.16 -VV Python 3.16.0b2 (v3.16.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)] ``` -------------------------------- ### Specify Package Dependencies and Download URL in Distutils setup() Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.5.rst Configure package metadata with requires, obsoletes, and download_url in setup(). Dependency information is saved into the PKG-INFO file when building distributions with sdist. ```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.tar.gz' % VERSION), ) ``` -------------------------------- ### Serve a WSGI application using setup_testing_defaults Source: https://github.com/python/cpython/blob/main/Doc/library/wsgiref.rst Populate the WSGI environment with default testing parameters and serve an application using make_server. This routine supplies dummy data for unit tests and should not be used in production servers or applications. ```python3 from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server # A relatively simple WSGI application. It's going to print out the # environment dictionary after being updated by setup_testing_defaults def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items()] return ret with make_server('', 8000, simple_app) as httpd: print("Serving on port 8000...") httpd.serve_forever() ``` -------------------------------- ### Get package version with importlib.metadata.version Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Retrieves the version string for an installed distribution package in the active Python environment. ```pycon (example) $ python >>> from importlib.metadata import version >>> version('wheel') '0.32.3' ``` -------------------------------- ### List all configure script options Source: https://github.com/python/cpython/blob/main/Doc/using/configure.rst Run this command to list all available options for the configure script. ```sh ./configure --help ``` -------------------------------- ### Create Testmapi.py using MAPI and win32api Source: https://github.com/python/cpython/blob/main/Tools/freeze/win32.html Initializes MAPI, queries the computer name via win32api, and uninitializes MAPI. ```python from win32com.mapi import mapi import win32api mapi.MAPIInitialize( (mapi.MAPI\_INIT\_VERSION, 0) ) print "Hello from", win32api.GetComputerName() mapi.MAPIUninitialize() ``` -------------------------------- ### str.title() basic example Source: https://github.com/python/cpython/blob/main/Doc/builtins/stdtypes.rst Returns a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase. ```python3 >>> 'Hello world'.title() 'Hello World' ``` -------------------------------- ### Get call count with call_count Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock.rst The call_count attribute is an integer that tracks how many times the mock has been called. It starts at 0 and increments with each call. ```pycon >>> mock = Mock(return_value=None) >>> mock.call_count 0 >>> mock() >>> mock() >>> mock.call_count 2 ``` -------------------------------- ### Batch site directory processing using site.StartupState Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Accumulates startup configuration data across multiple site directories to ensure all sys.path extensions are added before startup code runs. process() is not idempotent and must not be called more than once on the same instance. ```python state = site.StartupState() for sitedir in site_dirs: state.addsitedir(sitedir) state.process() ``` -------------------------------- ### Uninstall all managed runtimes with py uninstall --purge Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst Removes all runtimes managed by the Python install manager, including Start menu entries, registry settings, and download caches. Runtimes not installed by the manager and manually created configuration files are not affected. ```none $> py uninstall [-y|--yes] --purge ``` -------------------------------- ### Create basic Helloworld.py script Source: https://github.com/python/cpython/blob/main/Tools/freeze/win32.html Standard Python script demonstrating basic argument handling to be frozen. ```python import sys print " ".join( ["Hello", "world"] + sys.argv[1:] ) ``` -------------------------------- ### sys.base_prefix Source: https://github.com/python/cpython/blob/main/Doc/library/sys.rst Equivalent to prefix, but referring to the base Python installation. When running under virtual environment, prefix gets overwritten to the virtual environment prefix. base_prefix, conversely, does not change, and always points to the base Python installation. ```APIDOC ## sys.base_prefix ### Description Equivalent to `prefix`, but referring to the base Python installation. When running under virtual environment, `prefix` gets overwritten to the virtual environment prefix. `base_prefix`, conversely, does not change, and always points to the base Python installation. ### Type String ### Version Added in version 3.3. ``` -------------------------------- ### test.support.import_helper.modules_setup() Source: https://github.com/python/cpython/blob/main/Doc/library/test.rst Returns a copy of sys.modules. This function is used to capture the current state of imported modules. ```APIDOC ## test.support.import_helper.modules_setup() ### Description Return a copy of `sys.modules`. ### Method Function ### Endpoint test.support.import_helper.modules_setup() ### Parameters None ### Response Returns a copy of `sys.modules`. ``` -------------------------------- ### sys.base_exec_prefix Source: https://github.com/python/cpython/blob/main/Doc/library/sys.rst 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. ```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. ### Type String ### Version Added in version 3.3. ``` -------------------------------- ### class site.StartupState(known_paths=None) Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Accumulates interpreter startup configuration data from one or more site directories. It is the preferred interface for batching the processing of .pth and .start files across multiple directories. ```APIDOC ## site.StartupState(known_paths=None) ### Description Accumulates interpreter startup configuration data from one or more site directories. Used for batching the processing of `.pth` and `.start` files across multiple site directories so that every `sys.path` extension is visible before any startup code runs. ### Constructor Parameters - **known_paths** (set, optional) - A set of case-normalized paths used to prevent duplicate `sys.path` entries. Defaults to `None` (built from current `sys.path`). ### Methods - **addsitedir(sitedir)**: Reads `.pth` and `.start` files in `sitedir` and records `sys.path` extensions, deprecated `.pth` import lines, and `.start` entry points. - **addusersitepackages()**: Adds the per-user site-packages directory if enabled and existing. - **addsitepackages(prefixes=None)**: Adds global site-packages directories computed from `prefixes` (or global `PREFIXES` if `None`). - **process()**: Applies the accumulated state to `sys.path` and executes entry points and import lines. Must not be called more than once per instance. ### Usage Example ```python state = site.StartupState() for sitedir in site_dirs: state.addsitedir(sitedir) state.process() ``` ``` -------------------------------- ### Accepted traceback header lines Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst The expected output for an exception must start with one of these two traceback header lines, indented the same as the first line of the example. ```python3 Traceback (most recent call last): Traceback (innermost last): ``` -------------------------------- ### bytes.title example Source: https://github.com/python/cpython/blob/main/Doc/builtins/stdtypes.rst Returns a titlecased version where words start with an uppercase ASCII character and remaining characters are lowercase. Uncased byte values are left unmodified. ```python3 >>> b'Hello world'.title() b'Hello World' ``` -------------------------------- ### Display PC/layout help Source: https://github.com/python/cpython/blob/main/PC/layout/README.md Run the PC/layout script with `--help` using any Python 3 interpreter from the repository root to see available options. ```shell python PC/layout --help ``` -------------------------------- ### Define package hierarchies in setup.py with packages Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.0.rst Specify `packages` in `setup()` when the software consists of one or more Python packages and subpackages. This specifies directory hierarchies to package and install. ```python3 from distutils.core import setup setup (name = "foo", version = "1.0", packages = ["package", "package.subpackage"]) ``` -------------------------------- ### Run step-by-step configure and make targets Source: https://github.com/python/cpython/blob/main/Platforms/WASI/README.md Explicitly separates the configure and make steps for both the build Python and the WASI host. ```shell python3 Platforms/WASI configure-build-python -- --with-pydebug python3 Platforms/WASI make-build-python python3 Platforms/WASI configure-host python3 Platforms/WASI make-host ``` -------------------------------- ### Dictionary comprehension mapping names to functions Source: https://github.com/python/cpython/blob/main/Doc/reference/expressions.rst A dictionary comprehension starts with a colon-separated key-value pair. The example creates a dictionary mapping function names to function objects. ```python3 >>> {func.__name__: func for func in [print, hex, any]} {'print': <built-in function print>, 'hex': <built-in function hex>, 'any': <built-in function any>} ``` -------------------------------- ### Creating a PurePosixPath for parts demonstration Source: https://github.com/python/cpython/blob/main/Doc/library/pathlib.rst Example path used to illustrate the parent, name, stem, and suffix properties. ```python3 >>> p = PurePosixPath('/srv/holy/grail.tar.gz') ``` -------------------------------- ### Demonstrate CLI argument concepts using ls Source: https://github.com/python/cpython/blob/main/Doc/howto/argparse.rst Demonstrates basic command-line interface concepts such as running with default behavior, specifying positional directory arguments, applying optional flags like -l, and displaying help text with --help. ```shell-session $ ls cpython devguide prog.py pypy rm-unused-function.patch $ ls pypy ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l total 20 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch $ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. ... ``` -------------------------------- ### IsolatedAsyncioTestCase event order example Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.rst Illustrates the order in which setUp, asyncSetUp, test_response, asyncTearDown, tearDown, and cleanup are called. After running, events contains ["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]. ```python from unittest import IsolatedAsyncioTestCase events = [] class Test(IsolatedAsyncioTestCase): def setUp(self): events.append("setUp") async def asyncSetUp(self): self._async_connection = await AsyncConnection() events.append("asyncSetUp") async def test_response(self): events.append("test_response") response = await self._async_connection.get("https://example.com") self.assertEqual(response.status_code, 200) self.addAsyncCleanup(self.on_cleanup) def tearDown(self): events.append("tearDown") async def asyncTearDown(self): await self._async_connection.close() events.append("asyncTearDown") async def on_cleanup(self): events.append("cleanup") if __name__ == "__main__": unittest.main() ``` -------------------------------- ### Send data to CGI stdin and read response Source: https://github.com/python/cpython/blob/main/Doc/library/urllib.request.rst Sends a data stream to the stdin of a CGI script and reads the response. This example requires SSL support in the Python installation. ```python >>> import urllib.request >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi', ... data=b'This data is passed to stdin of the CGI') >>> with urllib.request.urlopen(req) as f: ... print(f.read().decode('utf-8')) ... Got Data: "This data is passed to stdin of the CGI" ``` -------------------------------- ### ,Run simple_logging_module.py and view console output Source: https://github.com/python/cpython/blob/main/Doc/howto/logging.rst ,Shows the command to run the explicit-code logging example and the resulting formatted log lines. The output includes timestamps, the simple_example logger name, level names, and messages. ```,shell-session ,$ python simple_logging_module.py 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message 2005-03-19 15:10:26,620 - simple_example - INFO - info message 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message 2005-03-19 15:10:26,697 - simple_example - ERROR - error message 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message ``` -------------------------------- ### enumerate() examples with default start and start=1 Source: https://github.com/python/cpython/blob/main/Doc/builtins/functions.rst Shows enumerate() on a list with default start=0 and with start=1. The output is a list of tuples containing a count and the value. ```pycon >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] ``` -------------------------------- ### os.startfile(path) Source: https://github.com/python/cpython/blob/main/Doc/library/os.rst Starts a file with its associated application. This acts like double-clicking the file in Windows Explorer. The function returns as soon as the application is launched; there is no option to wait for the application to close or retrieve its exit status. Available on Windows. ```APIDOC ## os.startfile(path) ### Description Start a file with its associated application. When *operation* is not specified, this acts like double-clicking the file in Windows Explorer. When another *operation* is given, it must be a “command verb” that specifies what should be done with the file. Common verbs are `'open'`, `'print'`, `'edit'`, `'explore'`, and `'find'`. ### Method Function ### Parameters - **path** (str) - Required - The file to start. Relative to the current directory or *cwd*. If you want to use an absolute path, make sure the first character is not a slash (`'/'`). Use `pathlib` or `os.path.normpath()` to ensure paths are properly encoded for Win32. - **operation** (str) - Optional - A “command verb” that specifies what should be done with the file. Default is `None` (acts like double-click). - **arguments** (str) - Optional - Arguments to be passed as a single string when launching an application. May have no effect when launching a document. - **cwd** (str) - Optional - The working directory. Should be an absolute path. A relative *path* will be resolved against this argument. - **show_cmd** (int) - Optional - Override the default window style. Values are integers as supported by the Win32 `ShellExecute()` function. ### Return Value None. The function returns as soon as the associated application is launched. ### Raises - **NotImplementedError** - If the Win32 `ShellExecute()` function cannot be resolved. ### Auditing Events - `os.startfile` with arguments `path`, `operation`. - `os.startfile/2` with arguments `path`, `operation`, `arguments`, `cwd`, `show_cmd`. ### Availability Windows ### Version Changed - Changed in version 3.10: Added the *arguments*, *cwd* and *show_cmd* arguments, and the `os.startfile/2` audit event. ``` -------------------------------- ### ,Configure logging with fileConfig and logging.conf Source: https://github.com/python/cpython/blob/main/Doc/howto/logging.rst ,Loads logging configuration from logging.conf using logging.config.fileConfig, then emits the same application log messages through the simpleExample logger. The logging.conf file must be present for this module to run. ```,python ,import logging import logging.config logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger('simpleExample') # 'application' code logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') ``` -------------------------------- ### test.support.reap_children() Source: https://github.com/python/cpython/blob/main/Doc/library/test.rst Call this from setUp(), tearDown(), or tearDownModule() in tests that start subprocesses. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks. ```APIDOC ## test.support.reap_children() ### Description Call this from setUp(), tearDown(), or tearDownModule() in tests that start subprocesses. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks. ### Method Function ### Endpoint test.support.reap_children ### Parameters None ### Response None ``` -------------------------------- ### Get a Distribution instance using importlib.metadata.distribution Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Call distribution() to obtain a concrete Distribution subclass instance for an installed package. Raises PackageNotFoundError if the package is not found in the current Python environment. ```python3 >>> from importlib.metadata import distribution >>> dist = distribution('wheel') >>> type(dist) <class 'importlib.metadata.PathDistribution'> ``` -------------------------------- ### Example command line with options and positional arguments Source: https://github.com/python/cpython/blob/main/Doc/library/optparse.rst Shows a sample command-line invocation combining flag options, options with arguments, and positional arguments. ```python3 prog -v --report report.txt foo bar ``` -------------------------------- ### multiprocessing.get_all_start_methods() Source: https://github.com/python/cpython/blob/main/Doc/library/multiprocessing.rst Returns a list of the supported start methods, the first of which is the default. The possible start methods are 'fork', 'spawn' and 'forkserver'. Not all platforms support all methods. ```APIDOC ## multiprocessing.get_all_start_methods() ### Description Returns a list of the supported start methods, the first of which is the default. The possible start methods are `'fork'`, `'spawn'` and `'forkserver'`. Not all platforms support all methods. ### Method Function call ### Endpoint `multiprocessing.get_all_start_methods()` ### Parameters None. ### Returns A list of strings representing supported start methods. ### Example ```python3 import multiprocessing methods = multiprocessing.get_all_start_methods() print(methods) # e.g., ['fork', 'spawn', 'forkserver'] ``` ``` -------------------------------- ### Deadlock example with Queue and join Source: https://github.com/python/cpython/blob/main/Doc/library/multiprocessing.rst A process puts a large item on a queue, then the parent joins before getting the item, causing a deadlock. The fix is to swap the last two lines or remove p.join(). ```python from multiprocessing import Process, Queue def f(q): q.put('X' * 1000000) if __name__ == '__main__': queue = Queue() p = Process(target=f, args=(queue,)) p.start() p.join() # this deadlocks obj = queue.get() ``` -------------------------------- ### int.bit_length() example Source: https://github.com/python/cpython/blob/main/Doc/builtins/stdtypes.rst Shows how to get the number of bits necessary to represent an integer in binary, excluding sign and leading zeros. For n = -37, bin(n) is '-0b100101' and n.bit_length() returns 6. ```python3 >>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6 ``` -------------------------------- ### setup_python(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist. On POSIX systems, a broken symlink at a destination path is removed before the copy or symlink is created. ```APIDOC ## setup_python(context) ### Description Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable `python3.x` was used, symlinks to `python` and `python3` will be created pointing to that executable, unless files with those names already exist. On POSIX systems, a broken symlink at a destination path is removed before the copy or symlink is created. ### Method setup_python ### Parameters - **context** (types.SimpleNamespace) - Required - The context object returned by `ensure_directories()`. ### Response None ### Version Changes - Changed in version 3.16: A broken symlink at a destination path is now removed and replaced. Previously it was left in place, or it made the copy fail. ``` -------------------------------- ### Install packages from requirements.txt Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst Use the environment's pip to install all packages listed in requirements.txt, which helps recreate the environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### Search online index for Python 3.16 with py list --online Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst The `--online` option searches the online index for installable runtimes. This example lists runtimes matching tag `3.16`. ```none $> py list --online 3.16 ```