### Python: unittest.TestCase Setup with Multiple Patcher Start/Stop Source: https://docs.python.org/3.13/library/unittest Provides an example of using patcher.start() and patcher.stop() within the setUp and tearDown methods of a unittest.TestCase for managing multiple patches. ```python import unittest from unittest.mock import patch # Assume package.module.Class1 and package.module.Class2 exist 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 # To run the test (example): # unittest.main() ``` -------------------------------- ### Python Logging Configuration Example Source: https://docs.python.org/3.13/howto/logging-cookbook Demonstrates basic logging setup in Python, including getting named loggers and emitting messages at different severity levels (debug, info, warning, error). This sets up the context for sending logs. ```python import logging logger1 = logging.getLogger('myapp.area1') logger2 = logging.getLogger('myapp.area2') logger1.debug('Quick zephyrs blow, vexing daft Jim.') logger1.info('How quickly daft jumping zebras vex.') logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') ``` -------------------------------- ### Silently Install Python via Command Prompt Source: https://docs.python.org/3.13/using/windows Demonstrates using the Python installer executable with command‑line switches to perform a silent, system‑wide installation or a customized per‑user install without the test suite. The examples show how to set options such as InstallAllUsers, Include_launcher, and SimpleInstall. Suitable for deployment scripts run from an elevated command prompt. ```batch python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0 python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0 SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite." ``` -------------------------------- ### Python: Multiprocessing Logging Setup and Execution Source: https://docs.python.org/3.13/howto/logging-cookbook Demonstrates the main execution flow for a multiprocessing logging system. It sets up initial logging, creates and starts multiple worker processes that send logs via a queue, starts a listener process to handle those logs, and manages the shutdown process for all components. ```python import logging import logging.config from multiprocessing import Process, Queue, Event # Assume worker_process, listener_process, q, stop_event, config_initial are defined elsewhere def main(): # Log some initial events, just to show that logging in the parent works # normally. logging.config.dictConfig(config_initial) logger = logging.getLogger('setup') logger.info('About to create workers ...') workers = [] for i in range(5): wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(config_worker,)) # config_worker defined previously workers.append(wp) wp.start() logger.info('Started worker: %s', wp.name) logger.info('About to create listener ...') stop_event = Event() lp = Process(target=listener_process, name='listener', args=(q, stop_event, config_listener)) # config_listener defined previously lp.start() logger.info('Started listener') # We now hang around for the workers to finish their work. for wp in workers: wp.join() # Workers all done, listening can now stop. # Logging in the parent still works normally. logger.info('Telling listener to stop ...') stop_event.set() lp.join() logger.info('All done.') if __name__ == '__main__': main() ``` -------------------------------- ### Python Setup for Custom Modules Source: https://docs.python.org/3.13/extending/newtypes_tutorial Configures the setup.py file using setuptools to build and install custom Python extension modules. It defines two extensions, 'custom' and 'custom2', each corresponding to a C source file ('custom.c' and 'custom2.c'). ```python from setuptools import Extension, setup setup(ext_modules=[ Extension("custom", ["custom.c"]), Extension("custom2", ["custom2.c"]), ]) ``` -------------------------------- ### Python Command Line Example Source: https://docs.python.org/3.13/library/optparse Shows an example of how to use the 'extend' action on the command line and the resulting list. ```python --names=foo,bar --names blah --names ding,dong ``` -------------------------------- ### Main Application Entry (Python) Source: https://docs.python.org/3.13/howto/logging-cookbook The main function that initializes the QApplication, sets up logging, creates the window instance, and starts the event loop. Handles both Qt5 and Qt6 exec method differences. ```python def main(): QtCore.QThread.currentThread().setObjectName('MainThread') logging.getLogger().setLevel(logging.DEBUG) app = QtWidgets.QApplication(sys.argv) example = Window(app) example.show() if hasattr(app, 'exec'): rc = app.exec() else: rc = app.exec_() sys.exit(rc) if __name__=='__main__': main() ``` -------------------------------- ### Python asyncio Hello World Example Source: https://docs.python.org/3.13/library/asyncio A simple 'Hello World' example demonstrating the basic usage of Python's asyncio library to run an asynchronous function. It prints messages with a delay, showcasing the async/await pattern for concurrent operations. ```python import asyncio async def main(): print('Hello ...') await asyncio.sleep(1) print('... World!') asyncio.run(main()) ``` -------------------------------- ### Get Start Attribute from Unicode Exception (C) Source: https://docs.python.org/3.13/c-api/exceptions Retrieves the start attribute from a given Unicode exception object and stores it in the provided Py_ssize_t pointer. The start pointer must not be NULL. Returns 0 on success and -1 on failure. This function is part of the Stable ABI. ```c int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) ``` -------------------------------- ### Python Doctest: Whitespace and Alignment in Examples Source: https://docs.python.org/3.13/library/doctest Shows how doctest handles leading whitespace in examples and expected output. It demonstrates that the starting column of the code prompt doesn't matter and that leading whitespace from the prompt is stripped from the expected output. ```python >>> assert "Easy!" >>> import math >>> math.floor(1.9) 1 ``` -------------------------------- ### Basic Logger Setup and Configuration - Python Source: https://docs.python.org/3.13/howto/logging-cookbook Demonstrates basic Python logging setup with multiple handlers (file and console), logger configuration, and module-based logging. Shows how to add handlers to a logger and configure different log levels for different output destinations. ```python import logging logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('spam.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) ``` -------------------------------- ### Python importlib.metadata for Package Information Source: https://docs.python.org/3.13/whatsnew/3 Shows how to use the importlib.metadata module to retrieve information about installed Python packages, such as version, dependencies, and files. This requires the 'requests' package to be installed for the example. ```python # Note following example requires that the popular "requests" # package has been installed. from importlib.metadata import version, requires, files version('requests') '2.22.0' list(requires('requests')) ['chardet (<3.1.0,>=3.0.2)'] list(files('requests'))[:5] [PackagePath('requests-2.22.0.dist-info/INSTALLER'), PackagePath('requests-2.22.0.dist-info/LICENSE'), PackagePath('requests-2.22.0.dist-info/METADATA'), PackagePath('requests-2.22.0.dist-info/RECORD'), PackagePath('requests-2.22.0.dist-info/WHEEL')] ``` -------------------------------- ### Creating a Basic HTTP Server Source: https://docs.python.org/3.13/library/http Example of how to create a simple HTTP server using `SimpleHTTPRequestHandler` to serve files from the current directory. ```APIDOC ## Create a Basic HTTP Server ### Description This code snippet demonstrates how to set up a basic HTTP server that serves files from the current directory using `http.server.SimpleHTTPRequestHandler`. ### Code Example ```python import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever() ``` ### Usage Run this Python script. The server will be accessible at `http://localhost:8000` (or the specified PORT), serving files from the directory where the script is executed. ``` -------------------------------- ### Configure default decimal context for all threads in Python Source: https://docs.python.org/3.13/library/decimal Sets application‑wide defaults for the decimal Context object before any threads start, ensuring consistent precision, rounding, and trap behavior across threads. Includes example of starting multiple threads after configuration. ```Python # Set application‑wide defaults for all threads about to be launched DefaultContext.prec = 12 DefaultContext.rounding = ROUND_DOWN DefaultContext.traps = ExtendedContext.traps.copy() DefaultContext.traps[InvalidOperation] = 1 setcontext(DefaultContext) # Afterwards, the threads can be started t1() t2.start() t3.start() # ... ``` -------------------------------- ### Get Installation Prefix (C API) Source: https://docs.python.org/3.13/c-api/init Returns the prefix for installed platform-independent files. This value is derived from the program name and environment variables. It corresponds to the `--prefix` configure argument. This function should not be called before `Py_Initialize()`. Deprecated since version 3.13. ```c wchar_t *Py_GetPrefix(); ``` -------------------------------- ### Python: Extend EnvBuilder to install setuptools and pip Source: https://docs.python.org/3.13/library/venv This Python script defines an `ExtendedEnvBuilder` class that inherits from `venv.EnvBuilder`. It overrides the `post_setup` method to automatically install setuptools and pip into the virtual environment after its creation. The `install_script` method handles downloading and executing installation scripts, with progress reporting capabilities. ```python import os import os.path from subprocess import Popen, PIPE import sys from threading import Thread from urllib.parse import urlparse from urllib.request import urlretrieve import venv class ExtendedEnvBuilder(venv.EnvBuilder): """ This builder installs setuptools and pip so that you can pip or easy_install other packages into the created virtual environment. :param nodist: If true, setuptools and pip are not installed into the created virtual environment. :param nopip: If true, pip is not installed into the created virtual environment. :param progress: If setuptools or pip are installed, the progress of the installation can be monitored by passing a progress callable. If specified, it is called with two arguments: a string indicating some progress, and a context indicating where the string is coming from. The context argument can have one of three values: 'main', indicating that it is called from virtualize() itself, and 'stdout' and 'stderr', which are obtained by reading lines from the output streams of a subprocess which is used to install the app. If a callable is not specified, default progress information is output to sys.stderr. """ def __init__(self, *args, **kwargs): self.nodist = kwargs.pop('nodist', False) self.nopip = kwargs.pop('nopip', False) self.progress = kwargs.pop('progress', None) self.verbose = kwargs.pop('verbose', False) super().__init__(*args, **kwargs) def post_setup(self, context): """ Set up any packages which need to be pre-installed into the virtual environment being created. :param context: The information for the virtual environment creation request being processed. """ os.environ['VIRTUAL_ENV'] = context.env_dir if not self.nodist: self.install_setuptools(context) # Can't install pip without setuptools if not self.nopip and not self.nodist: self.install_pip(context) def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. """ progress = self.progress while True: s = stream.readline() if not s: break if progress is not None: progress(s, context) else: if not self.verbose: sys.stderr.write('.') else: sys.stderr.write(s.decode('utf-8')) sys.stderr.flush() stream.close() def install_script(self, context, name, url): _, _, path, _, _, _ = urlparse(url) fn = os.path.split(path)[-1] binpath = context.bin_path distpath = os.path.join(binpath, fn) # Download script into the virtual environment's binaries folder urlretrieve(url, distpath) progress = self.progress if self.verbose: term = '\n' else: term = '' if progress is not None: progress('Installing %s ...%s' % (name, term), 'main') else: sys.stderr.write('Installing %s ...%s' % (name, term)) sys.stderr.flush() # Install in the virtual environment args = [context.env_exe, fn] p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) t1 = Thread(target=self.reader, args=(p.stdout, 'stdout')) t1.start() t2 = Thread(target=self.reader, args=(p.stderr, 'stderr')) t2.start() p.wait() t1.join() t2.join() if progress is not None: progress('done.', 'main') else: sys.stderr.write('done.\n') # Clean up - no longer needed os.unlink(distpath) def install_setuptools(self, context): """ Install setuptools in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = "https://bootstrap.pypa.io/ez_setup.py" self.install_script(context, 'setuptools', url) # clear up the setuptools archive which gets downloaded pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') files = filter(pred, os.listdir(context.bin_path)) for f in files: # The code snippet is truncated here, but this loop is intended to clean up downloaded archives. pass ``` -------------------------------- ### Python LoggerAdapter Initialization Example Source: https://docs.python.org/3.13/howto/logging-cookbook This Python code illustrates how to instantiate a `CustomAdapter`. It shows obtaining a logger instance and then creating an adapter instance, passing the logger and a dictionary containing contextual information ('connid'). ```python logger = logging.getLogger(__name__) adapter = CustomAdapter(logger, {'connid': some_conn_id}) ``` -------------------------------- ### Get Execution Prefix (C API) Source: https://docs.python.org/3.13/c-api/init Returns the execution prefix for installed platform-dependent files. This is derived similarly to the installation prefix but is used for files that vary by platform. It corresponds to the `--exec-prefix` configure argument. This function should not be called before `Py_Initialize()`. Deprecated since version 3.13. ```c wchar_t *Py_GetExecPrefix(); ``` -------------------------------- ### Python enumerate() Function Examples Source: https://docs.python.org/3.13/library/functions The enumerate() function returns an enumerate object, yielding pairs of count and value from an iterable. The count can be started from a specified value. ```python list(enumerate(seasons)) list(enumerate(seasons, start=1)) # Equivalent generator implementation def enumerate(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1 ``` -------------------------------- ### Database Initialization and Pickling Demo (Python) Source: https://docs.python.org/3.13/library/pickle Demonstrates usage of custom pickler/unpickler with an in-memory SQLite database. Shows complete workflow from database setup to pickling and unpickling operations. ```python def main(): import io import pprint conn = sqlite3.connect(":memory:") cursor = conn.cursor() cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)") tasks = ( 'give food to fish', 'prepare group meeting', 'fight with a zebra', ) for task in tasks: cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,)) cursor.execute("SELECT * FROM memos") memos = [MemoRecord(key, task) for key, task in cursor] file = io.BytesIO() DBPickler(file).dump(memos) print("Pickled records:") pprint.pprint(memos) cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1") file.seek(0) memos = DBUnpickler(file, conn).load() print("Unpickled records:") pprint.pprint(memos) ``` -------------------------------- ### Sample Python Script for Tokenization Source: https://docs.python.org/3.13/library/tokenize Simple Python function to print hello world, used as an example for tokenization. No dependencies required. Takes no inputs and prints a greeting to stdout. ```python def say_hello(): print("Hello, World!") say_hello() ``` -------------------------------- ### Python patch arbitrary attribute configuration example Source: https://docs.python.org/3.13/library/unittest This example shows how to pass arbitrary keyword arguments to patch to configure attributes on the created mock. It patches an object with first and second attributes set, starts the patcher, and asserts the mock has those attributes. Requires unittest.mock; inputs are the keyword args, outputs are attribute accesses on the mock. ```python >>> patcher = patch('__main__.thing', first='one', second='two') >>> mock_thing = patcher.start() >>> mock_thing.first 'one' >>> mock_thing.second 'two' ``` -------------------------------- ### Python asyncio REPL Example Source: https://docs.python.org/3.13/library/asyncio Demonstrates how to interact with the asyncio REPL (Read-Eval-Print Loop) from the command line. This allows for direct experimentation with asyncio functions, such as awaiting tasks, without needing to run a full script. It highlights the 'await' keyword's direct usability within the REPL. ```bash $ python -m asyncio ``` ```python asyncio REPL ... Use "await" directly instead of "asyncio.run()". Type "help", "copyright", "credits" or "license" for more information. >>> import asyncio >>> await asyncio.sleep(10, result='hello') 'hello' ``` -------------------------------- ### AsyncExitStack Usage Example in Python Source: https://docs.python.org/3.13/library/contextlib A placeholder example demonstrating the beginning of an `async with` block using `AsyncExitStack`. The actual implementation of context managers and cleanup logic would follow within this block. ```python async with AsyncExitStack() as stack: ``` -------------------------------- ### Python patch child mock configuration example Source: https://docs.python.org/3.13/library/unittest This example demonstrates configuring return_value and side_effect on child mocks via a dictionary expanded with **. It patches an object with method returning 3 and other raising KeyError, starts the patcher, and tests the behaviors. Requires unittest.mock; inputs are the config dict, outputs include return values and raised exceptions. ```python >>> config = {'method.return_value': 3, 'other.side_effect': KeyError} >>> patcher = patch('__main__.thing', **config) >>> mock_thing = patcher.start() >>> mock_thing.method() 3 >>> mock_thing.other() Traceback (most recent call last): ... KeyError ``` -------------------------------- ### AsyncIO Server Forever Serving Example in Python Source: https://docs.python.org/3.13/library/asyncio-eventloop Shows an example of defining a client connection handler and using serve_forever() to start accepting connections indefinitely. Depends on asyncio module and network parameters like host/port. The client_connected function processes incoming streams; server runs until cancelled, suitable for persistent services but not for timed shutdowns. ```python async def client_connected(reader, writer): # Communicate with the client with # reader/writer streams. For example: await reader.readline() async def main(host, port): srv = await asyncio.start_server( client_connected, host, port) await srv.serve_forever() asyncio.run(main('127.0.0.1', 0)) ``` -------------------------------- ### Python HTTP Basic Authentication Example Source: https://docs.python.org/3.13/howto/urllib2 This snippet demonstrates how to create an HTTP Basic Authentication handler and opener in Python. ```python import urllib.request # create a password manager password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of None. top_level_url = "http://example.com/foo/" password_mgr.add_password(None, top_level_url, username, password) handler = urllib.request.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib.request.build_opener(handler) # use the opener to fetch a URL # opener.open(a_url) # Install the opener. # Now all calls to urllib.request.urlopen use our opener. urllib.request.install_opener(opener) ``` -------------------------------- ### Setting and Getting the First Weekday in Python Calendar Source: https://docs.python.org/3.13/library/calendar Shows how to set and retrieve the starting day of the week for calendar generation in Python. This is useful for adapting calendars to different regional standards, such as starting the week on Sunday. The `setfirstweekday` function takes an integer representing the day (0 for Monday, 6 for Sunday), and `firstweekday` returns the current setting. ```python import calendar calendar.setfirstweekday(calendar.SUNDAY) print(calendar.firstweekday()) ``` -------------------------------- ### Prepare Python Binary Extension Modules as Frameworks (bash) Source: https://docs.python.org/3.13/using/ios Prepares compiled Python extension modules by packaging them as iOS frameworks. The script defines an install_dylib function that creates framework bundles, updates their Info.plist, and moves the binary into the framework. Add this script as a Run Script phase after the standard library installation. ```bash set -e\n\ninstall_dylib () {\n INSTALL_BASE=$1\n FULL_EXT=$2\n\n # The name of the extension file\n =$(basename \"$FULL_EXT\")\n # The location of the extension file, relative to the bundle\n RELATIVE_EXT=${FULL_EXT#$CODESIGNING_FOLDER_PATH/}\n # The path to the extension file, relative to the install base\n PYTHON_EXT=${RELATIVE_EXT/$INSTALL_BASE/}\n # The full dotted name of the extension module, constructed from the file path.\n FULL_MODULE_NAME=$(echo $PYTHON_EXT | cut -d "." -f 1 | tr "/" ".");\n # A bundle identifier; not actually used, but required by Xcode framework packaging\n FRAMEWORK_BUNDLE_ID=$(echo $PRODUCT_BUNDLE_IDENTIFIER.$FULL_MODULE_NAME | tr "_" "-");\n # The name of the framework folder.\n FRAMEWORK_FOLDER=\"Frameworks/$FULL_MODULE_NAME.framework\"\n\n # If the framework folder doesn't exist, create it.\n if [ ! -d \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER\" ]; then\n echo \"Creating framework for $RELATIVE_EXT\"\n mkdir -p \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER\"\n cp \"$CODESIGNING_FOLDER_PATH/dylib-Info-template.plist\" \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n plutil -replace CFBundleExecutable -string \"$FULL_MODULE_NAME\" \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n plutil -replace CFBundleIdentifier -string \"$FRAMEWORK_BUNDLE_ID\" \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/Info.plist\"\n fi\n\n echo \"Installing binary for $FRAMEWORK_FOLDER/$FULL_MODULE_NAME\"\n mv \"$FULL_EXT\" \"$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/$FULL_MODULE_NAME\"\n # Create a placeholder .fwork file where the .so was\n echo \"$FRAMEWORK_FOLDER/$FULL_MODULE_NAME\" > ${FULL_EXT%.so}.fwork\n} ``` -------------------------------- ### Python syslog with Options Source: https://docs.python.org/3.13/library/syslog This example shows how to use syslog with options such as including the process ID (LOG_PID) and specifying the mail logging facility (LOG_MAIL). It provides a more advanced logging setup. ```Python syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) syslog.syslog('E-mail processing initiated...') ``` -------------------------------- ### TopologicalSorter Static Order Example (Python) Source: https://docs.python.org/3.13/library/graphlib Demonstrates how to use the static_order() method of TopologicalSorter to get a linear ordering of nodes in a graph. This is useful for non-parallel processing. ```Python >>> graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}} >>> ts = TopologicalSorter(graph) >>> tuple(ts.static_order()) ('A', 'C', 'B', 'D') ``` -------------------------------- ### Python Setup Configuration for C Extension Source: https://docs.python.org/3.13/extending/newtypes_tutorial Uses setuptools to configure the build of a C extension module in setup.py. Specifies the extension name and source files for compilation into a shared library. ```python from setuptools import Extension, setup setup(ext_modules=[Extension("custom", ["custom.c"])]) ``` -------------------------------- ### Python Property() Usage Example Source: https://docs.python.org/3.13/howto/descriptor A typical use case of the `property()` function to define a managed attribute `x` within a class `C`. It utilizes getter, setter, and deleter methods. ```python class C: def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") ``` -------------------------------- ### Inspecting Dynamic C Extension Library (Python) Source: https://docs.python.org/3.13/using/configure This REPL example imports the _asyncio module, a dynamic C extension built as a shared library using Py_BUILD_CORE_MODULE. It displays the module with its file path and confirms the __file__ attribute points to the .so file. Requires the Python installation with dynamic extensions; outputs include the full path on Linux x86-64. ```python >>> import _asyncio >>> _asyncio >>> _asyncio.__file__ '/usr/lib64/python3.9/lib-dynload/_asyncio.cpython-39-x86_64-linux-gnu.so' ``` -------------------------------- ### Import and Initialize OptionParser in Python Source: https://docs.python.org/3.13/library/optparse This snippet demonstrates the initial steps for using the optparse module. It shows how to import the OptionParser class and create an instance of it, which is necessary before defining any command-line options. ```python from optparse import OptionParser ... parser = OptionParser() ``` -------------------------------- ### Python math.prod() function example Source: https://docs.python.org/3.13/whatsnew/3 Demonstrates the usage of the new `math.prod()` function, which calculates the product of an iterable of numbers, optionally with a starting value. This function is analogous to the built-in `sum()` function. ```python >>> prior = 0.8 >>> likelihoods = [0.625, 0.84, 0.30] >>> import math >>> math.prod(likelihoods, start=prior) 0.126 ``` -------------------------------- ### Example Virtual Environment Usage Source: https://docs.python.org/3.13/tutorial/venv Demonstrates activating a virtual environment and running Python interactively to inspect the system path. Requires an activated virtual environment. Input: Virtual environment activation. Output: Interactive Python session showing modified sys.path. Limitations: Example uses bash shell and specific Python version output; actual version may vary. ```bash $ source ~/envs/tutorial-env/bin/activate (tutorial-env) $ python Python 3.5.1 (default, May 6 2016, 10:59:36) ... >>> import sys >>> sys.path ['', '/usr/local/lib/python35.zip', ..., '~/envs/tutorial-env/lib/python3.5/site-packages'] >>> ``` -------------------------------- ### Patching with Class Decorators in Python Source: https://docs.python.org/3.13/library/unittest This example illustrates how to use patchers as class decorators, which wrap all test methods starting with a specified prefix (default: 'test'). It also shows how to customize the test prefix using `patch.TEST_PREFIX`. ```Python >>> patch.TEST_PREFIX = 'foo' >>> value = 3 >>> >>> @patch('__main__.value', 'not three') ... class Thing: ... def foo_one(self): ... print(value) ... def foo_two(self): ... print(value) ... >>> >>> Thing().foo_one() not three >>> Thing().foo_two() not three >>> value 3 ``` -------------------------------- ### PurePath Anchor Property Examples (Python) Source: https://docs.python.org/3.13/library/pathlib Shows the 'anchor' property, which is the combination of the drive and root of a path. This property is useful for identifying the fixed starting point of a path string. ```python >>> PureWindowsPath('c:/Program Files/').anchor 'c:\\' >>> PureWindowsPath('c:Program Files/').anchor 'c:' >>> PurePosixPath('/etc').anchor '/' >>> PureWindowsPath('//host/share').anchor '\\host\share\' ``` -------------------------------- ### Python: Basic String Formatting Examples Source: https://docs.python.org/3.13/library/string Demonstrates the basic usage of Python's str.format() method with positional and keyword arguments, attribute access, and indexing. ```python "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'. ``` -------------------------------- ### Basic Tkinter Hello World Program Source: https://docs.python.org/3.13/contents A foundational 'Hello World' example demonstrating how to create a basic Tkinter window and widget. This serves as an entry point for understanding Tkinter's event-driven model and widget creation. ```Python import tkinter as tk root = tk.Tk() root.title("Hello World") label = tk.Label(root, text="Hello, Tkinter!") label.pack() root.mainloop() ``` -------------------------------- ### Start Python Interactive Interpreter on Windows Source: https://docs.python.org/3.13/faq/windows Launches Python in interactive mode from Windows command prompt, allowing real-time Python statement execution and evaluation. Requires Python to be installed and accessible via 'py' command. ```bash C:\Users\YourName> py ``` ```python >>> print("Hello") Hello >>> "Hello" * 3 'HelloHelloHello' ``` -------------------------------- ### Install Python Extension Module Source: https://docs.python.org/3.13/extending/newtypes_tutorial Provides the command to install the Python extension module locally using pip. This command builds the C extensions defined in setup.py and makes them available for import in Python. ```bash python -m pip install . ``` -------------------------------- ### Python Locale Setting and String Comparison Example Source: https://docs.python.org/3.13/library/locale Demonstrates how to get the current locale, set it to German, perform a locale-aware string comparison with an umlaut, and then restore the original or C locale. This function requires the 'locale' module. ```python >>> import locale >>> loc = locale.getlocale() # get current locale # use German locale; name might vary with platform >>> locale.setlocale(locale.LC_ALL, 'de_DE') >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale ``` -------------------------------- ### Illustrate ConfigParser optionxform Method Override Source: https://docs.python.org/3.13/library/configparser This example demonstrates overriding the `optionxform` method in `ConfigParser`. This method is used to transform option names during read, get, or set operations. The default behavior converts names to lowercase. ```python import configparser class CustomOptionXFormParser(configparser.ConfigParser): def optionxform(self, optionstr): return optionstr.upper() # Example: convert to uppercase parser = CustomOptionXFormParser() parser.read_string('[Section]\nKey = Value') print(parser.options('Section')) ``` -------------------------------- ### Python: Interact with the Operating System using os module Source: https://docs.python.org/3.13/tutorial/stdlib Demonstrates basic operating system interactions like getting the current directory, changing directories, and running shell commands using the `os` module. It also shows how to use `dir()` and `help()` for module exploration. Avoid `from os import *` to prevent shadowing built-in functions. ```python >>> import os >>> os.getcwd() # Return the current working directory 'C:\Python313' >>> os.chdir('/server/accesslogs') # Change current working directory >>> os.system('mkdir today') # Run the command mkdir in the system shell 0 ``` ```python >>> import os >>> dir(os) >>> help(os) ```