### Basic Module Definition in Setup File Source: https://docs.python.org/3.9/install/index An example of a minimal entry in a Python extension's `Setup` file, defining a module named 'foo' from a single C source file 'foomodule.c'. ```text foo foomodule.c ``` -------------------------------- ### General Structure of a Setup File Line Source: https://docs.python.org/3.9/install/index Describes the generic syntax for a single line within a Python extension's `Setup` file, outlining the required module name and optional components like source files, C preprocessor arguments, and libraries. ```text module ... [sourcefile ...] [cpparg ...] [library ...] ``` -------------------------------- ### Manage Patches with setUp/tearDown (Python) Source: https://docs.python.org/3.9/library/unittest.mock-examples Illustrates how to manually manage patches by calling `patcher.start()` in the `setUp` method and `patcher.stop()` in the `tearDown` method of a `unittest.TestCase`. This approach provides explicit control over when a patch is active. ```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() ``` -------------------------------- ### Adding a Linker Library to a Setup File Entry Source: https://docs.python.org/3.9/install/index Demonstrates how to include a linker library, such as the math library (`-lm`), for a specific module within the Python extension's `Setup` file. ```text foo foomodule.c -lm ``` -------------------------------- ### Create a Windows Executable Installer for a Python Module Source: https://docs.python.org/3.9/distutils/introduction This command utilizes `distutils` to generate a self-contained executable installer (`.exe`) specifically for Windows platforms. This built distribution simplifies the installation process for end-users on Windows, providing a familiar click-through setup experience. ```python python setup.py bdist_wininst ``` -------------------------------- ### Setup Python Virtual Environment and Install Wheel Source: https://docs.python.org/3.9/library/importlib.metadata This snippet demonstrates the initial setup for working with Python packages. It covers creating a virtual environment, activating it, and installing a sample package ('wheel') using pip, which is a prerequisite for querying its metadata. ```bash python3 -m venv example source example/bin/activate pip install wheel ``` -------------------------------- ### setup.py install Command-Line Override Options Source: https://docs.python.org/3.9/install/index Reference for the command-line options available with `setup.py install` to customize the installation directories for different types of files. These options allow fine-grained control over where Python modules, scripts, data, and headers are placed during package installation. ```APIDOC setup.py install Options: --install-purelib: Python modules (pure Python) --install-platlib: Extension modules (platform-specific) --install-lib: All modules (overrides purelib/platlib) --install-scripts: Executable scripts --install-data: Data files --install-headers: C header files ``` -------------------------------- ### Customize Python Installation Directories via setup.py Source: https://docs.python.org/3.9/install/index Demonstrates various ways to override default installation paths for Python packages using `setup.py install` command-line options. Examples include specifying a home directory, absolute paths for scripts, and defining a full custom scheme with relative paths for different file types. ```bash python setup.py install --home=~ --install-scripts=scripts ``` ```bash python setup.py install --install-scripts=/usr/local/bin ``` ```bash python setup.py install --install-lib=Site ``` ```bash python setup.py install --home=~ \ --install-purelib=python/lib \ --install-platlib=python/lib.$PLAT \ --install-scripts=python/scripts --install-data=python/data ``` ```bash python setup.py install --home=~/python \ --install-purelib=lib \ --install-platlib='lib.$PLAT' \ --install-scripts=scripts --install-data=data ``` -------------------------------- ### Install Python Packages from requirements.txt Source: https://docs.python.org/3.9/tutorial/venv Demonstrates how to install all Python packages listed in a `requirements.txt` file using `pip install -r`, ensuring consistent environment setup. ```shell (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 ``` -------------------------------- ### Python Setup Installation with Custom Base Directory Source: https://docs.python.org/3.9/install/index Demonstrates how to use the `python setup.py install` command with the `--install-base` option to specify a custom root directory for package installation. This command overrides default paths, affecting where pure modules, platform-specific libraries, and scripts are ultimately placed. ```Shell python setup.py install --install-base=/tmp ``` -------------------------------- ### Python unittest.TestCase setUpClass Method Example Source: https://docs.python.org/3.9/library/unittest Example demonstrating the correct implementation of the `setUpClass` class method within a `unittest.TestCase` subclass, showing its decoration as a classmethod for class-level test setup. ```python @classmethod def setUpClass(cls): ... ``` -------------------------------- ### Windows Python Module Installation (Direct) Source: https://docs.python.org/3.9/install/index A simplified command for installing a Python module on Windows, typically run from a command prompt. This assumes `setup.py` is directly executable or Python is configured in the system's PATH. ```cmd setup.py install ``` -------------------------------- ### Install Python Package with Home Scheme to User Home Directory Source: https://docs.python.org/3.9/install/index Shows a shortcut for installing a Python package into the user's home directory using the `--home=~` option with `setup.py`. The `install` command expands the tilde (`~`) to the user's home directory. ```bash python setup.py install --home=~ ``` -------------------------------- ### Navigate and Install Python Module on Windows Source: https://docs.python.org/3.9/install/index Commands for Windows users to navigate to the unpacked directory of a Python module distribution and then execute the standard installation command. This assumes the archive has already been extracted. ```cmd cd c:\Temp\foo-1.0 python setup.py install ``` -------------------------------- ### Example: Reading Multiple Configuration Files (Python configparser) Source: https://docs.python.org/3.9/library/configparser This example demonstrates how to use `configparser.ConfigParser` to read a default configuration file using `read_file` and then overlay additional configurations from user-specific and site-wide files using `read` with a specified encoding. ```python import configparser, os config = configparser.ConfigParser() config.read_file(open('defaults.cfg')) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250') ``` -------------------------------- ### Split Build and Install for Python Modules Source: https://docs.python.org/3.9/install/index Commands to perform the build and install steps of a Python module distribution incrementally. This approach is useful for debugging, customization, or when different users/privileges are required for each phase. ```python python setup.py build python setup.py install ``` -------------------------------- ### Install Python Packages with Specific Python Versions (Windows) Source: https://docs.python.org/3.9/installing/index Illustrates how to use the `py` Python launcher on Windows to install packages with pip for a specific Python interpreter version. ```Shell py -2 -m pip install SomePackage # default Python 2 py -2.7 -m pip install SomePackage # specifically Python 2.7 py -3 -m pip install SomePackage # default Python 3 py -3.4 -m pip install SomePackage # specifically Python 3.4 ``` -------------------------------- ### Install Python on OpenBSD using pkg_add Source: https://docs.python.org/3.9/using/unix These commands illustrate different ways to install Python on OpenBSD using the `pkg_add` utility. It includes a general command for the latest version, a generic URL-based installation, and a specific example for Python 2.5.1. ```Shell pkg_add -r python ``` ```Shell pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz ``` ```Shell pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### Install Specific or Minimum Python Package Version Source: https://docs.python.org/3.9/installing/index Demonstrates how to install a precise version of a Python package or a version meeting a minimum requirement using pip, handling shell special characters with quotes. ```Shell python -m pip install SomePackage==1.0.4 # specific version python -m pip install "SomePackage>=1.0.4" # minimum version ``` -------------------------------- ### Install Python Modules to /usr/local on Unix Source: https://docs.python.org/3.9/install/index Demonstrates how to install Python modules from source to a specific prefix, such as /usr/local, when the system Python is located in /usr, ensuring modules are placed in a traditional local add-on path. ```bash /usr/bin/python setup.py install --prefix=/usr/local ``` -------------------------------- ### Comprehensive INI File Structure Example Source: https://docs.python.org/3.9/library/configparser Presents a detailed example of an INI configuration file, showcasing various features supported by `configparser`. This includes sections, key-value pairs with different delimiters, comments, multiline values, and handling of whitespace and empty values. ```INI [Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too? ``` -------------------------------- ### Unpack and Install Python Module on Unix/Linux Source: https://docs.python.org/3.9/install/index A sequence of commands for Unix-like systems to unpack a gzipped tar archive containing a Python module distribution, navigate into its directory, and then perform the standard installation. ```bash gunzip -c foo-1.0.tar.gz | tar xf - cd foo-1.0 python setup.py install ``` -------------------------------- ### Displaying Options for a Distutils Command Source: https://docs.python.org/3.9/distutils/configfile Demonstrates how to use the `--help` option with `setup.py` to list available options for a specific Distutils command, such as `build_ext`. This output helps users understand configurable parameters and their descriptions. ```Shell $ python setup.py --help build_ext [...] Options for 'build_ext' command: --build-lib (-b) directory for compiled extension modules --build-temp (-t) directory for temporary files (build by-products) --inplace (-i) ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules --include-dirs (-I) list of directories to search for header files --define (-D) C preprocessor macros to define --undef (-U) C preprocessor macros to undefine --swig-opts list of SWIG command line options [...] ``` -------------------------------- ### Install Python Package with User Scheme Source: https://docs.python.org/3.9/install/index Demonstrates how to install a Python package into the user's site-packages directory using `setup.py` with the `--user` option. This method is convenient for users without write permissions to global site-packages directories, placing files under `site.USER_BASE`. ```bash python setup.py install --user ``` -------------------------------- ### distutils.core.setup() Keyword Arguments Reference Source: https://docs.python.org/3.9/distutils/setupscript Comprehensive documentation for keyword arguments of the `distutils.core.setup()` function, detailing options for building extensions and managing package relationships (requires, provides, obsoletes). ```APIDOC distutils.core.setup( optional: bool = False, description: If true, a build failure in the extension will not abort the build process, but instead simply not install the failing extension. extra_objects: list[str], description: List of object files to be passed to the linker. These files must not have extensions, as the default extension for the compiler is used. extra_compile_args: list[str], description: Additional command line options for the respective compiler. extra_link_args: list[str], description: Additional command line options for the respective linker. export_symbols: list[str], description: (Windows only) List of symbols (functions or variables) to be exported. This option is not needed when building compiled extensions: Distutils will automatically add `initmodule` to the list of exported symbols. depends: list[str], description: List of files that the extension depends on (for example header files). The build command will call the compiler on the sources to rebuild extension if any on this files has been modified since the previous build. requires: list[str], description: Specifies dependencies on other Python modules and packages. The value must be a list of strings. Each string specifies a package that is required, and optionally what versions are sufficient. Examples: 'mymodule', 'xml.parsers.expat', '>1.0, !=1.5.1, <2.0'. provides: list[str], description: Declares packages or modules provided by the distribution. The value is a list of strings, each naming a Python module or package, and optionally identifying the version. Examples: 'mypkg', 'mypkg (1.1)'. obsoletes: list[str], description: Declares that this package obsoletes other packages. The value is a list of strings giving module or package specifiers, similar to 'requires', with optional version qualifiers. ) ``` -------------------------------- ### Extract Package Metadata with importlib.metadata Source: https://docs.python.org/3.9/whatsnew/3.8 Demonstrates how to use the new `importlib.metadata` module to programmatically retrieve metadata from installed third-party packages. This example shows how to get a package's version, list its requirements, and inspect its installed files. It requires the 'requests' package to be installed for the example to run. ```python from importlib.metadata import version, requires, files version('requests') list(requires('requests')) list(files('requests'))[:5] ``` -------------------------------- ### Configure Python Installation Options via unattend.xml Source: https://docs.python.org/3.9/using/windows This XML snippet defines installation options for Python 3.9, mirroring the 'just for me' command-line example. When placed as 'unattend.xml' alongside the installer executable, it automates the setup process without requiring command-line arguments. ```XML ``` -------------------------------- ### Basic Syntax for setup.cfg Configuration File Source: https://docs.python.org/3.9/distutils/configfile Illustrates the fundamental structure of a `setup.cfg` file, showing how to define options under specific command sections. Each section starts with a command name in brackets, followed by key-value pairs for options. ```INI [command] option=value ... ``` -------------------------------- ### Install a Python Module from a Source Distribution Source: https://docs.python.org/3.9/distutils/introduction After downloading and unpacking a source distribution, this command is used to install the Python module. It copies the module files (e.g., `foo.py`) to the appropriate directory within the user's Python installation, making the module available for import. ```python python setup.py install ``` -------------------------------- ### setup.py for Multiple Pure Python Modules Source: https://docs.python.org/3.9/distutils/examples This `setup.py` script provides an example for packaging multiple pure Python modules (`foo` and `bar`) into a single distribution named 'foobar'. It utilizes the `py_modules` option to list all modules included in the distribution. ```Python from distutils.core import setup setup(name='foobar', version='1.0', py_modules=['foo', 'bar'], ) ``` -------------------------------- ### Define a Basic Python Module Distribution with Distutils Source: https://docs.python.org/3.9/distutils/setupscript This example demonstrates a `setup.py` script using `distutils.core.setup`. It defines essential metadata such as the project name, version, description, author, and URL. It also specifies the Python packages to be included in the distribution, which is crucial for packaging multi-module projects. ```python #!/usr/bin/env python from distutils.core import setup setup(name='Distutils', version='1.0', description='Python Distribution Utilities', author='Greg Ward', author_email='gward@python.net', url='https://www.python.org/sigs/distutils-sig/', packages=['distutils', 'distutils.command'], ) ``` -------------------------------- ### Minimal setup.py for Single Python Module Source: https://docs.python.org/3.9/distutils/examples This code demonstrates a basic `setup.py` script using `distutils.core.setup` to define a distribution named 'foo' with version '1.0'. It includes the 'foo' module by listing it in the `py_modules` option, which is suitable for individual modules not part of a larger package. ```Python from distutils.core import setup setup(name='foo', version='1.0', py_modules=['foo'], ) ``` -------------------------------- ### Install Python Modules to Network Path on Unix Source: https://docs.python.org/3.9/install/index Illustrates installing Python modules to a network filesystem path using --prefix when the name used to write to a remote directory differs from the name used to read it, common in complex network setups. ```bash /usr/local/bin/python setup.py install --prefix=/mnt/@server/export ``` -------------------------------- ### Example Python Generator Class Definition Source: https://docs.python.org/3.9/library/unittest.mock-examples Defines a simple Python class `Foo` with an `iter` method that acts as a generator, yielding a sequence of numbers. This class serves as a concrete example for demonstrating how to mock generator methods and their iteration behavior. ```Python >>> class Foo: ... def iter(self): ... for i in [1, 2, 3]: ... yield i ... >>> foo = Foo() >>> list(foo.iter()) [1, 2, 3] ``` -------------------------------- ### Define Minimal setup.py for Metadata Check Source: https://docs.python.org/3.9/distutils/examples This Python `setup.py` script defines a basic package with only a `name`. It serves as an example to demonstrate the warnings generated by the `distutils check` command when essential metadata fields are missing. ```Python from distutils.core import setup setup(name='foobar') ``` -------------------------------- ### Display Options for a Specific Distutils Command Source: https://docs.python.org/3.9/install/index This shell command demonstrates how to use the '--help' option with 'setup.py' to view all available command-line options for a particular Distutils command, such as 'build'. ```Shell python setup.py build --help ``` -------------------------------- ### Distutils Default Installation Path Configuration Source: https://docs.python.org/3.9/install/index Illustrates common configuration variables used in Distutils configuration files to define default installation directories for platform-specific libraries, scripts, and data. These variables guide where different components of a Python package are placed during installation. ```Configuration install-platlib=lib.$PLAT install-scripts=scripts install-data=data ``` -------------------------------- ### Complete Setup Script for a Single Extension Source: https://docs.python.org/3.9/distutils/setupscript Shows a full `setup.py` script demonstrating how to integrate the `Extension` definition into a `setup()` call for a module distribution containing a single extension. ```Python from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` -------------------------------- ### Define a Basic Python Module Setup Script Source: https://docs.python.org/3.9/distutils/introduction This Python script, typically named `setup.py`, uses `distutils.core.setup` to define a simple module named 'foo'. It specifies the module's name, version, and lists the pure Python modules it contains (in this case, 'foo.py'). This script is the core configuration for packaging your Python project. ```python from distutils.core import setup setup(name='foo', version='1.0', py_modules=['foo'], ) ``` -------------------------------- ### Ensure Patch Cleanup with addCleanup (Python) Source: https://docs.python.org/3.9/library/unittest.mock-examples Shows how to use `unittest.TestCase.addCleanup()` to ensure that `patcher.stop()` is reliably called after a test, even if an exception occurs during `setUp`. This prevents patches from leaking between tests and improves test isolation. ```Python class MyTest(unittest.TestCase): def setUp(self): patcher = patch('mymodule.foo') self.addCleanup(patcher.stop) self.mock_foo = patcher.start() def test_foo(self): self.assertIs(mymodule.foo, self.mock_foo) MyTest('test_foo').run() ``` -------------------------------- ### Query Package Name from setup.py Command Line Source: https://docs.python.org/3.9/distutils/examples Demonstrates how to retrieve specific package metadata, such as the `name`, directly from a `setup.py` script using a command-line argument. This leverages the `distutils.core.setup()` function's built-in command-line interface to query metadata fields. The output for this command is `distribute`. ```Shell $ python setup.py --name ``` -------------------------------- ### Decorating unittest.TestCase Methods with patch.object Source: https://docs.python.org/3.9/library/unittest.mock-examples This example demonstrates a common pattern of applying `patch.object` directly as a decorator to a method within a `unittest.TestCase` class. The patch is active only for the duration of that specific test method, ensuring isolation between tests. ```Python >>> class MyTest(unittest.TestCase): ... @patch.object(SomeClass, 'attribute', sentinel.attribute) ... def test_something(self): ... self.assertEqual(SomeClass.attribute, sentinel.attribute) ... >>> original = SomeClass.attribute >>> MyTest('test_something').test_something() >>> assert SomeClass.attribute == original ``` -------------------------------- ### Execute Python setup.py build with custom base directory Source: https://docs.python.org/3.9/install/index Demonstrates how to run the `setup.py build` command, specifying a custom build base directory using the `--build-base` option. This allows users to control where the built files are temporarily stored, useful for maintaining a pristine source tree or managing build artifacts. ```bash python setup.py build --build-base=/path/to/pybuild/foo-1.0 ``` -------------------------------- ### Assigning a MagicMock to an Object Method Source: https://docs.python.org/3.9/library/unittest.mock-examples Demonstrates how to replace an existing method on an object with a `MagicMock` instance. This allows for recording calls and making assertions about method usage. The example shows calling the mocked method with positional and keyword arguments. ```python real = SomeClass() real.method = MagicMock(name='method') real.method(3, 4, 5, key='value') ``` -------------------------------- ### Specifying Arbitrary Compiler and Linker Flags Source: https://docs.python.org/3.9/install/index Illustrates the use of `-Xcompiler` and `-Xlinker` options in the `Setup` file to pass custom, arbitrary flags directly to the compiler (e.g., `-o32`) and linker (e.g., `-shared`), along with a library. ```text foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm ``` -------------------------------- ### Shebang Line with Interpreter Arguments Source: https://docs.python.org/3.9/using/windows This shebang line demonstrates how to pass command-line arguments directly to the Python interpreter. In this example, the `-v` option is passed, which causes the Python interpreter to start in verbose mode, printing module initialization messages. ```Python #! /usr/bin/python -v ``` -------------------------------- ### Minimal setup.py for Python modules Source: https://docs.python.org/3.9/whatsnew/2.0 This snippet shows a basic `setup.py` script using `distutils.core.setup` for a project containing only Python (`.py`) files. It defines the project name, version, and lists the modules to be installed, simplifying the distribution process. ```Python from distutils.core import setup setup (name = "foo", version = "1.0", py_modules = ["module1", "module2"]) ``` -------------------------------- ### Temporarily Modifying Dictionaries with patch.dict Source: https://docs.python.org/3.9/library/unittest.mock-examples This example demonstrates `patch.dict` used as a context manager to temporarily modify a dictionary. It shows how to add new keys or clear existing ones, ensuring that the dictionary is automatically restored to its original state once the `with` block is exited. ```Python >>> foo = {'key': 'value'} >>> original = foo.copy() >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): ... assert foo == {'newkey': 'newvalue'} ... >>> assert foo == original ``` -------------------------------- ### Display Global Distutils Options Source: https://docs.python.org/3.9/install/index This shell command shows how to use the '--help' option with 'setup.py' without a specific command to list all global options that affect Distutils operations. ```Shell python setup.py --help ``` -------------------------------- ### Configure Package Data Installation with Distutils Source: https://docs.python.org/3.9/distutils/setupscript This example illustrates how to include non-code data files, such as `.dat` files, directly within a Python package during installation. It uses the `package_data` keyword argument in `setup()` to map package names to a list of relative paths for data files, supporting glob patterns. The `package_dir` option is also shown for mapping source directories. ```python setup(..., packages=['mypkg'], package_dir={'mypkg': 'src/mypkg'}, package_data={'mypkg': ['data/*.dat']}, ) ``` -------------------------------- ### Demonstrating `Matcher` Failure with Incorrect Values Source: https://docs.python.org/3.9/library/unittest.mock-examples This example shows that the custom `Matcher` correctly raises an `AssertionError` when the object passed to the mock does not match the criteria defined by the `Matcher`'s comparison function. It confirms that the custom matching logic is effectively enforcing the desired assertion. ```Python from unittest.mock import Mock # Assuming Foo, compare, and Matcher classes are defined as above class Foo: def __init__(self, a, b): self.a, self.b = a, b def compare(self, other): if not type(self) == type(other): return False if self.a != other.a: return False if self.b != other.b: return False return True class Matcher: def __init__(self, compare, some_obj): self.compare = compare self.some_obj = some_obj def __eq__(self, other): return self.compare(self.some_obj, other) mock = Mock(return_value=None) mock(Foo(1, 2)) match_wrong = Matcher(compare, Foo(3, 4)) mock.assert_called_with(match_wrong) ``` -------------------------------- ### Install Standard Python Packaging Tools Source: https://docs.python.org/3.9/distributing/index This command installs the essential Python packaging and distribution tools: 'setuptools' for package definition, 'wheel' for creating binary distribution packages, and 'twine' for securely uploading packages to PyPI. It uses the 'python -m pip' syntax to ensure the correct pip executable associated with the current Python environment is used. ```bash python -m pip install setuptools wheel twine ``` -------------------------------- ### Track and Assert Call Order with Parent Mock Source: https://docs.python.org/3.9/library/unittest.mock-examples This example demonstrates how to use a parent `Mock` object to aggregate and track calls made to its dynamically created child mocks. It shows how `manager.mock_calls` records the sequence of calls and how to assert this sequence against an expected list of `call` objects. ```python manager = Mock() mock_foo = manager.foo mock_bar = manager.bar mock_foo.something() mock_bar.other.thing() # manager.mock_calls will be [call.foo.something(), call.bar.other.thing()] expected_calls = [call.foo.something(), call.bar.other.thing()] manager.mock_calls == expected_calls # Expected output: True ``` -------------------------------- ### EnvBuilder.post_setup Method Documentation Source: https://docs.python.org/3.9/library/venv Documents the `post_setup` method of the `EnvBuilder` class, which serves as a placeholder for third-party implementations to perform custom actions such as pre-installing packages or other post-creation steps after the virtual environment is set up. ```APIDOC class EnvBuilder: post_setup(*context) 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. Parameters: context: The context object for the environment builder. ``` -------------------------------- ### Install Latest Python Package with pip Source: https://docs.python.org/3.9/installing/index Installs the latest available version of a specified Python package and its dependencies from the Python Package Index using pip. ```Shell python -m pip install SomePackage ``` -------------------------------- ### Distutils setup.py for Python packages Source: https://docs.python.org/3.9/whatsnew/2.0 This example demonstrates how to configure `setup.py` using `distutils.core.setup` when your software is organized into Python packages. It specifies the project name, version, and lists the packages to be included, ensuring proper installation of the package structure. ```Python from distutils.core import setup setup (name = "foo", version = "1.0", packages = ["package", "package.subpackage"]) ``` -------------------------------- ### Memoryview __eq__ Method Setup Example Source: https://docs.python.org/3.9/library/stdtypes This partial example demonstrates the initial setup for comparing memoryviews using the `__eq__` method, specifically showing the creation of an `array.array` object that could be used as an operand in such a comparison. ```python import array a = array.array('I', [1, 2, 3, 4, 5]) ``` -------------------------------- ### Execute distutils check Command Source: https://docs.python.org/3.9/distutils/examples Runs the `distutils check` command on a minimal `setup.py` to identify missing required metadata. The output shows warnings for absent version, URL, author, and maintainer information, highlighting the command's validation capabilities: ``` running check warning: check: missing required meta-data: version, url warning: check: missing meta-data: either (author and author_email) or (maintainer and maintainer_email) should be supplied ``` ```Shell $ python setup.py check ``` -------------------------------- ### Example INI Configuration File Structure Source: https://docs.python.org/3.9/library/configparser A basic INI-style configuration file demonstrating sections like `DEFAULT`, `bitbucket.org`, and `topsecret.server.com` with key-value pairs. This structure is parsed by `configparser`. ```ini [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no ``` -------------------------------- ### Example Class with Chained Method Calls Source: https://docs.python.org/3.9/library/unittest.mock-examples Provides a sample Python class `Something` that contains a method `method` which makes a series of chained calls to an internal `backend` object. This snippet sets up a realistic scenario for demonstrating how to effectively mock such complex chained calls for testing purposes. ```python >>> class Something: ... def __init__(self): ... self.backend = BackendProvider() ... def method(self): ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() ... # more code ``` -------------------------------- ### EnvBuilder.setup_scripts Method Documentation Source: https://docs.python.org/3.9/library/venv Documents the `setup_scripts` method of the `EnvBuilder` class, which is responsible for installing platform-appropriate activation scripts into a virtual environment. ```APIDOC class EnvBuilder: setup_scripts(*context) Installs activation scripts appropriate to the platform into the virtual environment. Parameters: context: The context object for the environment builder. ``` -------------------------------- ### Distutils setup.py for C extension modules Source: https://docs.python.org/3.9/whatsnew/2.0 This advanced `setup.py` script illustrates how to build a C extension module using `distutils.core.setup` and `distutils.core.Extension`. It defines the extension's name, include directories, source files, and preprocessor macros, enabling compilation and installation of native code components within a Python package. ```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 ] ) ``` -------------------------------- ### Assert Specific Call Sequence with assert_has_calls Source: https://docs.python.org/3.9/library/unittest.mock-examples This example demonstrates the use of `assert_has_calls` to verify if a specific sequence of calls has occurred on a mock. It shows how to construct a `call_list` from chained `call` objects and use it to assert the presence of that exact sequence within the mock's `mock_calls`, even if other calls were made. ```python m = MagicMock() m().foo().bar().baz() m.one().two().three() calls = call.one().two().three().call_list() m.assert_has_calls(calls) ``` -------------------------------- ### Building Extensions In-Place via Command Line Source: https://docs.python.org/3.9/distutils/configfile Shows the command-line invocation to build Python extensions directly within their source directory using the `--inplace` option with the `build_ext` command. This approach requires explicit specification for each build. ```Shell python setup.py build_ext --inplace ``` -------------------------------- ### Patching Built-in Functions with patch as a Context Manager Source: https://docs.python.org/3.9/library/unittest.mock-examples This example illustrates using `patch` as a context manager to temporarily replace a built-in function, such as `open`. It demonstrates how to mock the function's behavior and assert that it was called with the expected arguments, ensuring the original function is restored upon exiting the `with` block. ```Python >>> mock = MagicMock(return_value=sentinel.file_handle) >>> with patch('builtins.open', mock): ... handle = open('filename', 'r') ... >>> mock.assert_called_with('filename', 'r') >>> assert handle == sentinel.file_handle, "incorrect file handle returned" ``` -------------------------------- ### Mocking Class Instantiation with unittest.mock.patch Source: https://docs.python.org/3.9/library/unittest.mock-examples This example illustrates how to mock an entire class that is instantiated within a function. By using `unittest.mock.patch`, the original class is replaced with a mock, allowing control over the return value of the mocked instance. It demonstrates setting `return_value` on the mock to control the behavior of the mocked class instance. ```python >>> def some_function(): ... instance = module.Foo() ... return instance.method() ... >>> with patch('module.Foo') as mock: ... instance = mock.return_value ... instance.method.return_value = 'the result' ... result = some_function() ... assert result == 'the result' ``` -------------------------------- ### Configure Basic Python Package Distribution (Root Package) Source: https://docs.python.org/3.9/distutils/examples Demonstrates the simplest `setup.py` configuration using `distutils` to distribute modules located directly in the root package. The empty string in the `packages` list signifies the root package. ```Python from distutils.core import setup setup(name='foobar', version='1.0', packages=[''], ) ``` -------------------------------- ### Verify Python Version from nuget.org Installation Source: https://docs.python.org/3.9/using/windows Examples demonstrating how to execute the installed Python interpreter and check its version after installation via nuget.exe. It shows the path variations depending on whether the `-ExcludeVersion` option was used during installation, illustrating that the `tools` directory contains the Python executable. ```Batch # Without -ExcludeVersion > .\python.3.5.2\tools\python.exe -V Python 3.5.2 # With -ExcludeVersion > .\python\tools\python.exe -V Python 3.5.2 ``` -------------------------------- ### Python: Programmatically Create and Write INI Configuration File Source: https://docs.python.org/3.9/library/configparser Demonstrates using Python's `configparser` module to create a `ConfigParser` object, populate it with sections and key-value pairs, and write the configuration to an INI file named `example.ini`. ```python import configparser config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile) ``` -------------------------------- ### Define Custom Installation Scheme in Distutils Config Source: https://docs.python.org/3.9/install/index Shows how to persist a custom installation scheme by adding options to the Distutils configuration file. This allows for consistent installations without repeating extensive command-line arguments for every package. ```ini [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-data=python/data ``` ```ini [install] install-base=$HOME/python install-purelib=lib ``` -------------------------------- ### Retrieve Python Installation Prefixes (sys.prefix, sys.exec_prefix) Source: https://docs.python.org/3.9/install/index This Python interactive session demonstrates how to use the `sys` module to find the `prefix` and `exec_prefix` directories of the current Python installation. These paths indicate where Python is installed and where it finds its libraries at runtime. ```Python Python 2.4 (#26, Aug 7 2004, 17:19:02) Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.prefix '/usr' >>> sys.exec_prefix '/usr' ``` -------------------------------- ### Install Python Packages with Specific Python Versions (POSIX) Source: https://docs.python.org/3.9/installing/index Shows how to use versioned Python commands on Linux, macOS, and other POSIX systems to install packages with pip for a particular Python interpreter. ```Shell python2 -m pip install SomePackage # default Python 2 python2.7 -m pip install SomePackage # specifically Python 2.7 python3 -m pip install SomePackage # default Python 3 python3.4 -m pip install SomePackage # specifically Python 3.4 ``` -------------------------------- ### Define Python Package Metadata with distutils.core.setup Source: https://docs.python.org/3.9/distutils/apiref The `setup()` function is the primary entry point for defining a Python package's metadata and build configuration using Distutils. It accepts numerous arguments to specify package name, version, description, author, modules, scripts, and more. ```APIDOC distutils.core.setup(*arguments) Description: The basic do-everything function that does most everything you could ever ask for from a Distutils method. Arguments: - name (string): The name of the package - version (string): The version number of the package; see distutils.version - description (string): A single line describing the package - long_description (string): Longer description of the package - author (string): The name of the package author - author_email (string): The email address of the package author - maintainer (string): The name of the current maintainer, if different from the author. Note that if the maintainer is provided, distutils will use it as the author in PKG-INFO - maintainer_email (string): The email address of the current maintainer, if different from the author - url (string): A URL for the package (homepage) - download_url (string): A URL to download the package - packages (list of strings): A list of Python packages that distutils will manipulate - py_modules (list of strings): A list of Python modules that distutils will manipulate - scripts (list of strings): A list of standalone script files to be built and installed - ext_modules (list of instances of distutils.core.Extension): A list of Python extensions to be built - classifiers (list of strings): A list of categories for the package; valid classifiers are listed on PyPI. - distclass (subclass of distutils.core.Distribution): the Distribution class to use - script_name (string): The name of the setup.py script - defaults to sys.argv[0] - script_args (list of strings): Arguments to supply to the setup script - options (dictionary): default options for the setup script - license (string): The license for the package - keywords (list of strings or a comma-separated string): Descriptive meta-data, see PEP 314 - platforms (list of strings or a comma-separated string): - cmdclass (dictionary): A mapping of command names to Command subclasses - data_files (list): A list of data files to install - package_dir (dictionary): A mapping of package to directory names ``` -------------------------------- ### Standard Python Module Installation Source: https://docs.python.org/3.9/install/index The most common command to build and install a Python module distribution packaged with Distutils. This single command handles both the compilation/packaging and the placement of files into the Python environment. ```python python setup.py install ``` -------------------------------- ### Configuring In-Place Build for Extensions in setup.cfg Source: https://docs.python.org/3.9/distutils/configfile Provides an example of setting the `inplace` option for the `build_ext` command within `setup.cfg`. This configuration persists the setting, eliminating the need to specify it on the command line for every build. ```INI [build_ext] inplace=1 ``` -------------------------------- ### Configuring RPM Distribution Options in setup.cfg Source: https://docs.python.org/3.9/distutils/configfile Illustrates how to define multiple options for the `bdist_rpm` command within `setup.cfg`. This allows for persistent configuration of RPM-specific metadata like release number, packager information, and documentation files, avoiding repetitive command-line input. ```INI [bdist_rpm] release = 1 packager = Greg Ward doc_files = CHANGES.txt ``` -------------------------------- ### Define Basic Python C Extension with distutils setup.py Source: https://docs.python.org/3.9/extending/building This `setup.py` script defines a simple Python extension module named 'demo' from a single C source file 'demo.c' using `distutils`. It sets up basic package metadata like name, version, and description. ```Python from distutils.core import setup, Extension module1 = Extension('demo', sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ``` -------------------------------- ### Example Usage of setup_testing_defaults Source: https://docs.python.org/3.9/library/wsgiref This Python example demonstrates how to use `wsgiref.util.setup_testing_defaults` within a simple WSGI application. It shows how the `environ` dictionary is updated with default values for testing purposes, which can then be inspected or used by the application. ```Python 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") ``` -------------------------------- ### Ensure pip is installed for Python Source: https://docs.python.org/3.9/installing/index This command uses the `ensurepip` module to install or upgrade the default `pip` package installer for the current Python environment. It is a common solution when `pip` is not found or needs to be re-initialized, especially in Python versions where `pip` might not be bundled by default. ```bash python -m ensurepip --default-pip ```