### Starting Server to Accept Connections Forever Source: https://docs.python.org/3.13/library/asyncio-eventloop.html This example demonstrates how to start a server and keep it accepting connections indefinitely until the task is cancelled. It includes a basic client connection handler. ```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)) ``` -------------------------------- ### Basic SimpleXMLRPCServer Setup Source: https://docs.python.org/3.13/library/xmlrpc.server.html This snippet shows the basic setup for a SimpleXMLRPCServer, including specifying the host, port, and request handler. It also demonstrates how to register functions and start the server. ```python from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) # Create and run the server. with SimpleXMLRPCServer(("localhost", 8000), requestHandler=RequestHandler) as server: server.register_introspection_functions() def adder_function(x, y): return x + y server.register_function(adder_function, "add") # Register a class instance class MyFuncs: def multiply(self, x, y): return x * y server.register_instance(MyFuncs()) server.serve_forever() ``` -------------------------------- ### Create and Start Threads with `threading.Thread` Source: https://docs.python.org/3.13/library/threading.html Demonstrates the basic usage of creating and starting threads using the `threading.Thread` class. This example simulates I/O-bound tasks using `time.sleep`. ```Python import threading import time def crawl(link, delay=3): print(f"crawl started for {link}") time.sleep(delay) # Blocking I/O (simulating a network request) print(f"crawl ended for {link}") links = [ "https://python.org", "https://docs.python.org", "https://peps.python.org", ] ``` -------------------------------- ### HTTP GET Request Example Source: https://docs.python.org/3.13/library/http.client.html Demonstrates a basic HTTP GET request to retrieve the content of the root path. Shows how to get the response status, reason, and read the entire response body. ```python import http.client conn = http.client.HTTPSConnection("www.python.org") conn.request("GET", "/") r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() # This will return entire content. ``` -------------------------------- ### Install a package using pip Source: https://docs.python.org/3.13/library/importlib.metadata.html Demonstrates the commands to create a virtual environment and install the 'wheel' package using pip. ```bash $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### Command-line Execution of XML-RPC Server Demo Source: https://docs.python.org/3.13/library/xmlrpc.server.html Shows how to run the example XML-RPC server directly from the command line using the python -m xmlrpc.server command. This is a convenient way to start the server without writing a separate script. ```bash python -m xmlrpc.server ``` -------------------------------- ### Example Command-Line Structure Source: https://docs.python.org/3.13/library/optparse.html Provides an example of a typical command-line structure, identifying options, option arguments, and positional arguments. ```text prog -v --report report.txt foo bar ``` -------------------------------- ### Install pip Source: https://docs.python.org/3.13/library/ensurepip.html Use this command to install pip if it is not already present. It will not upgrade an existing installation. ```bash python -m ensurepip ``` -------------------------------- ### Hello World Asyncio Example Source: https://docs.python.org/3.13/library/asyncio.html A basic example demonstrating the 'Hello World!' output using asyncio's async/await syntax and running a coroutine. ```python import asyncio async def main(): print('Hello ...') await asyncio.sleep(1) print('... World!') asyncio.run(main()) ``` -------------------------------- ### Get first weekday setting Source: https://docs.python.org/3.13/library/calendar.html Retrieves the current setting for the weekday that starts each week. No setup is required. ```python import calendar calendar.firstweekday() ``` -------------------------------- ### setup_scripts Source: https://docs.python.org/3.13/library/venv.html Installs activation scripts appropriate to the platform into the virtual environment. ```APIDOC ## setup_scripts ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Parameters * `_context_` - The context for the environment creation. ``` -------------------------------- ### Perform a GET request using HTTPSConnection Source: https://docs.python.org/3.13/library/http.client.html This example demonstrates how to perform a GET request to a secure HTTPS URL using the `HTTPSConnection` class. It shows the necessary imports, connection setup, request sending, and how to retrieve and print the response status and reason. ```Python import http.client host = "docs.python.org" conn = http.client.HTTPSConnection(host) conn.request("GET", "/3/", headers={"Host": host}) response = conn.getresponse() print(response.status, response.reason) ``` -------------------------------- ### Get Distribution Version Source: https://docs.python.org/3.13/library/importlib.metadata.html Retrieves the installed version of a specified distribution package. Raises PackageNotFoundError if the package is not installed. ```python from importlib.metadata import version version('wheel') '0.32.3' ``` -------------------------------- ### Client Usage Example Source: https://docs.python.org/3.13/library/xmlrpc.client.html A basic example demonstrating how to use ServerProxy to make a call to a remote XML-RPC service. ```APIDOC ## Example of Client Usage ### Description This example shows a simple program to interact with an XML-RPC server using `ServerProxy`. ### Code ```python from xmlrpc.client import ServerProxy, Error # Use a context manager for ServerProxy with ServerProxy("http://betty.userland.com") as proxy: print(proxy) try: # Call a method on the remote server print(proxy.examples.getStateName(41)) except Error as v: print("ERROR", v) ``` ``` -------------------------------- ### Using enumerate with default start Source: https://docs.python.org/3.13/library/functions.html Demonstrates how to use the enumerate function to get index-value pairs from an iterable, starting the count from 0. ```python >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] ``` -------------------------------- ### Install Setuptools and Pip in Virtual Environment Source: https://docs.python.org/3.13/library/venv.html Installs setuptools and pip into a virtual environment. It downloads the necessary scripts from bootstrap.pypa.io and cleans up downloaded archives. ```python 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: f = os.path.join(context.bin_path, f) os.unlink(f) def install_pip(self, context): """ Install pip in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = 'https://bootstrap.pypa.io/get-pip.py' self.install_script(context, 'pip', url) ``` -------------------------------- ### Server.start_serving() Source: https://docs.python.org/3.13/library/asyncio-eventloop.html Initiates the server to start accepting incoming network connections. This method is idempotent and can be safely called even if the server is already serving connections. ```APIDOC ## Server.start_serving() ### Description Start accepting connections. This method is idempotent, so it can be called when the server is already serving. The `_start_serving` keyword-only parameter to `loop.create_server()` and `asyncio.start_server()` allows creating a Server object that is not accepting connections initially. In this case `Server.start_serving()`, or `Server.serve_forever()` can be used to make the Server start accepting connections. ### Method `_async _start_serving()` ### Added in version 3.7 ``` -------------------------------- ### DocTestParser Source: https://docs.python.org/3.13/library/doctest.html A class for extracting interactive examples from a string and creating DocTest objects. It provides methods to get doctests, examples, and parse strings. ```APIDOC ## Class: DocTestParser ### Description Extracts interactive examples from strings to create `DocTest` objects. It is used to parse docstrings and identify testable examples. ### Methods #### get_doctest(_string_ , _globs_ , _name_ , _filename_ , _lineno_) ##### Description Extracts all doctest examples from the given string and collects them into a `DocTest` object. ##### Parameters - `_string_` (str) - The string to parse for doctests. - `_globs_` (dict) - Attributes for the new `DocTest` object. - `_name_` (str) - Optional - A name identifying this string, used for error messages. Defaults to ''. - `_filename_` (str) - Optional - The filename associated with the string. - `_lineno_` (int) - Optional - The line number where the string originates. #### get_examples(_string_ , _name =''_) ##### Description Extracts all doctest examples from the given string and returns them as a list of `Example` objects. Line numbers are 0-based. ##### Parameters - `_string_` (str) - The string to extract examples from. - `_name_` (str) - Optional - A name identifying this string, used for error messages. Defaults to ''. #### parse(_string_ , _name =''_) ##### Description Divides the given string into examples and intervening text, returning them as a list of alternating `Example`s and strings. Line numbers for the `Example`s are 0-based. ##### Parameters - `_string_` (str) - The string to parse. - `_name_` (str) - Optional - A name identifying this string, used for error messages. Defaults to ''. ### Related Classes - `DocTestFinder` - `DocTest` - `Example` ``` -------------------------------- ### Patching in setUp and tearDown with unittest.TestCase Source: https://docs.python.org/3.13/library/unittest.mock.html Manage multiple patches within a TestCase's setUp and tearDown methods. Ensure patches are started in setUp and stopped in tearDown to maintain a clean state for each test. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` -------------------------------- ### Example .pth File Configuration Source: https://docs.python.org/3.13/library/site.html This example shows the contents of a .pth file and how it affects the sys.path. Lines starting with '#' are comments, and existing directories are added to sys.path. ```python # foo package configuration foo bar bletch ``` -------------------------------- ### Basic FTP Session Example Source: https://docs.python.org/3.13/library/ftplib.html Demonstrates a typical FTP session including connecting, logging in, changing directories, listing contents, downloading a file, and quitting. ```python from ftplib import FTP ftp = FTP('ftp.us.debian.org') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ ftp.cwd('debian') # change into "debian" directory ftp.retrlines('LIST') # list directory contents with open('README', 'wb') as fp: ftp.retrbinary('RETR README', fp.write) ftp.quit() ``` -------------------------------- ### Asynchronous Test Case Example Source: https://docs.python.org/3.13/library/unittest.html Demonstrates the execution order of setup, test, and teardown methods in an asynchronous test case using IsolatedAsyncioTestCase. Includes setup, async setup, the test method, async teardown, and cleanup. ```python from unittest import IsolatedAsyncioTestCase import unittest events = [] class Test(IsolatedAsyncioTestCase): def setUp(self): events.append("setUp") async def asyncSetUp(self): # Assuming AsyncConnection is a mock or real async class # self._async_connection = await AsyncConnection() events.append("asyncSetUp") async def test_response(self): events.append("test_response") # Assuming _async_connection has a get method # 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): # Assuming _async_connection has a close method # await self._async_connection.close() events.append("asyncTearDown") async def on_cleanup(self): events.append("cleanup") if __name__ == "__main__": unittest.main() ``` -------------------------------- ### setup_python Source: https://docs.python.org/3.13/library/venv.html Creates a copy or symlink to the Python executable in the virtual environment. ```APIDOC ## setup_python ### 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. ### Parameters * `_context_` - The context for the environment creation. ``` -------------------------------- ### Get Package Version Source: https://docs.python.org/3.13/library/importlib.metadata.html Retrieve the version string for an installed distribution package. ```APIDOC ## version(name) ### Description Returns the version string for the named distribution package. ### Parameters #### Path Parameters - **name** (str) - Required - The name of the distribution package. ### Request Example ```python from importlib.metadata import version version('wheel') ``` ### Response #### Success Response (200) - **version_string** (str) - The version of the package. ``` -------------------------------- ### Basic Application Logging Setup Source: https://docs.python.org/3.13/library/logging.html Sets up basic logging for an application, directing INFO level messages to a file named 'myapp.log'. This is useful for simple applications where a single log file is sufficient. ```python import logging import mylib logger = logging.getLogger(__name__) def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO) logger.info('Started') mylib.do_something() logger.info('Finished') if __name__ == '__main__': main() ``` -------------------------------- ### post_setup Source: https://docs.python.org/3.13/library/venv.html A placeholder method that can be overridden for post-creation steps. ```APIDOC ## post_setup ### 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. ### Parameters * `_context_` - The context for the environment creation. ``` -------------------------------- ### test.support.import_helper.modules_setup Source: https://docs.python.org/3.13/library/test.html Returns a copy of the current sys.modules dictionary. ```APIDOC ## test.support.import_helper.modules_setup ### Description Return a copy of `sys.modules`. ### Parameters None ``` -------------------------------- ### Standard Formats Examples (64-bit) Source: https://docs.python.org/3.13/library/struct.html Demonstrates the use of standard format strings with explicit byte ordering and alignment on a 64-bit machine. Shows how pack and calcsize behave with different format codes. ```python >>> calcsize('>> pack('>> calcsize('@llh') 18 >>> pack('@llh', 1, 2, 3) == pack('>> calcsize('>> calcsize('@llh0l') 24 >>> pack('@llh0l', 1, 2, 3) == pack('>> requires('wheel') ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"] ``` -------------------------------- ### Get package metadata Source: https://docs.python.org/3.13/library/importlib.metadata.html Illustrates how to retrieve a list of metadata keys for an installed package. ```python from importlib.metadata import metadata list(metadata('wheel')) ``` -------------------------------- ### Query all entry points Source: https://docs.python.org/3.13/library/importlib.metadata.html Demonstrates how to get a collection of all entry points for the current environment. ```python from importlib.metadata import entry_points eps = entry_points() ``` -------------------------------- ### BytesIO getbuffer() Example Source: https://docs.python.org/3.13/library/io.html Demonstrates how to get a mutable view of the BytesIO buffer and modify its contents. ```python import io b = io.BytesIO(b"abcdef") view = b.getbuffer() view[2:4] = b"56" print(b.getvalue()) ``` -------------------------------- ### Running an HTTP Server Source: https://docs.python.org/3.13/library/http.server.html This example demonstrates how to create and run a basic HTTP server using HTTPServer and BaseHTTPRequestHandler. ```APIDOC ## Running an HTTP Server This function sets up and runs an HTTP server. ### Function Signature ```python def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler): server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.serve_forever() ``` ### Parameters - **server_class** (class) - The server class to use, defaults to `HTTPServer`. - **handler_class** (class) - The request handler class to use, defaults to `BaseHTTPRequestHandler`. ``` -------------------------------- ### Create an ArgumentParser Instance Source: https://docs.python.org/3.13/library/argparse.html Instantiate `ArgumentParser` to configure the parser with program name, description, and epilog text displayed in the help message. ```python parser = argparse.ArgumentParser( prog='ProgramName', description='What the program does', epilog='Text at the bottom of help') ``` -------------------------------- ### tracemalloc.get_traceback_limit() Source: https://docs.python.org/3.13/library/tracemalloc.html Gets the maximum number of frames stored in the traceback of a trace. This limit is set by the `start()` function. ```APIDOC ## tracemalloc.get_traceback_limit() ### Description Get the maximum number of frames stored in the traceback of a trace. The `tracemalloc` module must be tracing memory allocations to get the limit, otherwise an exception is raised. The limit is set by the `start()` function. ``` -------------------------------- ### Timing user-defined functions with setup import Source: https://docs.python.org/3.13/library/timeit.html Shows how to time a user-defined function by importing it into the timeit environment using the 'setup' parameter. ```python def test(): """Stupid test function""" L = [i for i in range(100)] if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) ``` -------------------------------- ### Get Distribution Metadata Source: https://docs.python.org/3.13/library/importlib.metadata.html Retrieves the metadata for a specified distribution package. Raises PackageNotFoundError if the package is not installed. ```python from importlib.metadata import metadata wheel_metadata = metadata('wheel') ``` -------------------------------- ### Example Usage Source: https://docs.python.org/3.13/library/urllib.robotparser.html Demonstrates basic usage of the RobotFileParser class for setting URL, reading robots.txt, and checking fetch permissions. ```python import urllib.robotparser rp = urllib.robotparser.RobotFileParser() rp.set_url("http://www.pythontest.net/robots.txt") rp.read() rrate = rp.request_rate("*") print(f"Request rate: {rrate.requests} requests per {rrate.seconds} seconds") crawl_delay = rp.crawl_delay("*") print(f"Crawl delay: {crawl_delay} seconds") can_fetch_root = rp.can_fetch("*", "http://www.pythontest.net/") print(f"Can fetch root: {can_fetch_root}") can_fetch_other = rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/") print(f"Can fetch other: {can_fetch_other}") ``` -------------------------------- ### Get package version Source: https://docs.python.org/3.13/library/importlib.metadata.html Shows how to import the 'version' function and retrieve the version string of an installed package. ```python from importlib.metadata import version version('wheel') ``` -------------------------------- ### Access Distribution version Source: https://docs.python.org/3.13/library/importlib.metadata.html Get the version of an installed distribution package from its `Distribution` instance's `.version` attribute. ```python >>> dist.version '0.32.3' ``` -------------------------------- ### Example .pth File Configuration (Second) Source: https://docs.python.org/3.13/library/site.html This example shows another .pth file. The order of directories added to sys.path depends on the alphabetical order of .pth filenames. ```python # bar package configuration bar ``` -------------------------------- ### Command-line Execution of XML-RPC Client Demo Source: https://docs.python.org/3.13/library/xmlrpc.server.html Demonstrates how to run the example XML-RPC client from the command line using the python -m xmlrpc.client command. This is useful for testing client-server interactions. ```bash python -m xmlrpc.client ``` -------------------------------- ### Locate Distribution File Path Source: https://docs.python.org/3.13/library/importlib.metadata.html Get the absolute filesystem path to a file within an installed distribution package. ```python >>> util.locate() PosixPath('/home/gustav/example/lib/site-packages/wheel/util.py') ``` -------------------------------- ### Get Distribution Files Source: https://docs.python.org/3.13/library/importlib.metadata.html Retrieve all files associated with an installed distribution package. Returns None if metadata is missing. ```python >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0] >>> util PackagePath('wheel/util.py') >>> util.size 859 >>> util.dist >>> util.hash ``` -------------------------------- ### bin() function examples Source: https://docs.python.org/3.13/library/functions.html Demonstrates converting integers to binary strings using the bin() function and the format() function. ```Python >>> bin(3) '0b11' >>> bin(-10) '-0b1010' ``` ```Python >>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') ``` -------------------------------- ### _asyncSetUp() Source: https://docs.python.org/3.13/library/unittest.html Asynchronous method called to prepare the test fixture after `TestCase.setUp()`, immediately before the test method. ```APIDOC ## _async _asyncSetUp() ### Description Method called to prepare the test fixture. This is called after `TestCase.setUp()`. This is called immediately before calling the test method; other than `AssertionError` or `SkipTest`, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing. ### Method N/A (Async Instance Method) ``` -------------------------------- ### itertools.islice Usage Examples Source: https://docs.python.org/3.13/library/itertools.html These examples demonstrate the usage of itertools.islice for creating an iterator that returns selected elements from an iterable, similar to sequence slicing but without negative indices. It supports specifying start, stop, and step parameters. ```python def islice(iterable, *args): # islice('ABCDEFG', 2) → A B # islice('ABCDEFG', 2, 4) → C D # islice('ABCDEFG', 2, None) → C D E F G # islice('ABCDEFG', 0, None, 2) → A C E G s = slice(*args) start = 0 if s.start is None else s.start stop = s.stop step = 1 if s.step is None else s.step if start < 0 or (stop is not None and stop < 0) or step <= 0: raise ValueError indices = count() if stop is None else range(max(start, stop)) next_i = start for i, element in zip(indices, iterable): if i == next_i: yield element next_i += step ``` -------------------------------- ### Dictionary Creation Examples Source: https://docs.python.org/3.13/library/stdtypes.html Demonstrates multiple ways to create dictionaries that are equal in content, including using keyword arguments, literal syntax, `zip`, and combining methods. All examples result in the same dictionary. ```python >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True ``` -------------------------------- ### Example of using ioctl to get process group ID Source: https://docs.python.org/3.13/library/fcntl.html This example demonstrates how to use `fcntl.ioctl` with `termios.TIOCGPGRP` to retrieve the process group ID associated with a file descriptor. It shows both direct integer return and mutation of a buffer. ```python import array, fcntl, struct, termios, os os.getpgrp() struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] buf = array.array('h', [0]) cntl.ioctl(0, termios.TIOCGPGRP, buf, 1) buf ``` -------------------------------- ### Generated Help Output Example Source: https://docs.python.org/3.13/library/optparse.html An example of the automatically generated help message for a script using optparse, detailing the usage and available options. ```text Usage: [options] Options: -h, --help show this help message and exit -f FILE, --file=FILE write report to FILE -q, --quiet don't print status messages to stdout ``` -------------------------------- ### tracemalloc.start(_nframe_) Source: https://docs.python.org/3.13/library/tracemalloc.html Starts tracing Python memory allocations by installing hooks. It can limit the number of frames collected in tracebacks. ```APIDOC ## tracemalloc.start(_nframe_ : int = 1) ### Description Start tracing Python memory allocations: install hooks on Python memory allocators. Collected tracebacks of traces will be limited to _nframe_ frames. By default, a trace of a memory block only stores the most recent frame: the limit is `1`. _nframe_ must be greater or equal to `1`. You can still read the original number of total frames that composed the traceback by looking at the `Traceback.total_nframe` attribute. Storing more than `1` frame is only useful to compute statistics grouped by `'traceback'` or to compute cumulative statistics: see the `Snapshot.compare_to()` and `Snapshot.statistics()` methods. Storing more frames increases the memory and CPU overhead of the `tracemalloc` module. Use the `get_tracemalloc_memory()` function to measure how much memory is used by the `tracemalloc` module. The `PYTHONTRACEMALLOC` environment variable (`PYTHONTRACEMALLOC=NFRAME`) and the `-X` `tracemalloc=NFRAME` command line option can be used to start tracing at startup. See also `stop()`, `is_tracing()` and `get_traceback_limit()` functions. ``` -------------------------------- ### unittest TestCase with setUp and tearDown Source: https://docs.python.org/3.13/library/unittest.html Use `setUp()` to prepare a test fixture before each test method runs, and `tearDown()` to clean up resources afterward. These methods are automatically called by the testing framework. ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def test_default_widget_size(self): self.assertEqual(self.widget.size(), (50,50), 'incorrect default size') def test_widget_resize(self): self.widget.resize(100,150) self.assertEqual(self.widget.size(), (100,150), 'wrong size after resize') ``` ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() ``` -------------------------------- ### Check Platform with sys.platform Source: https://docs.python.org/3.13/library/sys.html Use sys.platform to check the operating system. This example shows how to test if the platform starts with 'freebsd'. ```python import sys if sys.platform.startswith('freebsd'): # FreeBSD-specific code here... pass ``` -------------------------------- ### Command-Line Interface Examples Source: https://docs.python.org/3.13/library/timeit.html Compares the performance of three different string formatting methods using the command-line interface. ```bash $ python -m timeit "'-'.join(str(n) for n in range(100))" 10000 loops, best of 5: 30.2 usec per loop $ python -m timeit "'-'.join([str(n) for n in range(100)])" 10000 loops, best of 5: 27.5 usec per loop $ python -m timeit "'-'.join(map(str, range(100)))" 10000 loops, best of 5: 23.2 usec per loop ``` -------------------------------- ### Namespace Object Example Source: https://docs.python.org/3.13/library/multiprocessing.html Demonstrates creating and accessing attributes of a shared Namespace object using a manager. Attributes starting with '_' are local to the proxy. ```python mp_context = multiprocessing.get_context('spawn') manager = mp_context.Manager() Global = manager.Namespace() Global.x = 10 Global.y = 'hello' Global._z = 12.3 # this is an attribute of the proxy print(Global) ``` -------------------------------- ### Example Source: https://docs.python.org/3.13/library/copyreg.html Demonstrates how to register a pickle function and its usage. ```APIDOC ## Example ### Description The example below would like to show how to register a pickle function and how it will be used: ### Request Example ```python >>> import copyreg, copy, pickle >>> class C: ... def __init__(self, a): ... self.a = a ... >>> def pickle_c(c): ... print("pickling a C instance...") ... return C, (c.a,) ... >>> copyreg.pickle(C, pickle_c) >>> c = C(1) >>> d = copy.copy(c) pickling a C instance... >>> p = pickle.dumps(c) pickling a C instance... ``` ``` -------------------------------- ### Get Stack Source: https://docs.python.org/3.13/library/inspect.html Returns a list of `FrameInfo` objects for the caller's entire stack, starting with the immediate caller and ending with the outermost call. ```python inspect.stack(_context =1_) ``` -------------------------------- ### UDP Client Setup Source: https://docs.python.org/3.13/library/socketserver.html Initializes a UDP client to send data to a server. Requires HOST, PORT, and data to be defined. ```python import socket import sys HOST, PORT = "localhost", 9999 data = " ".join(sys.argv[1:]) ``` -------------------------------- ### Iterate and Filter Directory Entries with os.scandir Source: https://docs.python.org/3.13/library/os.html Use os.scandir() with a 'with' statement for automatic resource management. This example filters for files that do not start with a dot. ```python with os.scandir(path) as it: for entry in it: if not entry.name.startswith('.') and entry.is_file(): print(entry.name) ``` -------------------------------- ### Basic Usage Example Source: https://docs.python.org/3.13/library/shelve.html Demonstrates the fundamental operations of opening a shelf, storing, retrieving, deleting, and checking for keys, along with considerations for mutable objects when `writeback` is `False`. ```APIDOC ## Example To summarize the interface (`key` is a string, `data` is an arbitrary object): ```python import shelve d = shelve.open(filename) # open -- file may get suffix added by low-level # library d[key] = data # store data at key (overwrites old data if # using an existing key) data = d[key] # retrieve a COPY of data at key (raise KeyError # if no such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = key in d # true if the key exists klist = list(d.keys()) # a list of all existing keys (slow!) # as d was opened WITHOUT writeback=True, beware: d['xx'] = [0, 1, 2] # this works as expected, but... d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]! # having opened d without writeback=True, you need to code carefully: temp = d['xx'] # extracts the copy temp.append(5) # mutates the copy d['xx'] = temp # stores the copy right back, to persist it # or, d=shelve.open(filename,writeback=True) would let you just code # d['xx'].append(5) and have it work as expected, BUT it would also # consume more memory and make the d.close() operation slower. ``` ``` -------------------------------- ### Pattern.search() Example Source: https://docs.python.org/3.13/library/re.html Scans through a string looking for the first location where the regular expression produces a match. The optional `pos` parameter specifies the starting index for the search. ```python >>> pattern = re.compile("d") >>> pattern.search("dog") # Match at index 0 >>> pattern.search("dog", 1) # No match; search doesn't include the "d" ``` -------------------------------- ### Example command line for 'extend' action Source: https://docs.python.org/3.13/library/optparse.html Demonstrates how to use the 'extend' action with comma-separated values and multiple occurrences of the option on the command line. ```Shell --names=foo,bar --names blah --names ding,dong ``` -------------------------------- ### Get Help for Functional bgcolor Source: https://docs.python.org/3.13/library/turtle.html Access the docstring for the functional version of bgcolor using help(). This version is derived from the Screen method and shows its arguments and examples. ```python >>> help(bgcolor) Help on function bgcolor in module turtle: bgcolor(*args) Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example:: >>> bgcolor("orange") >>> bgcolor() "orange" >>> bgcolor(0.5,0,0.5) >>> bgcolor() "#800080" ``` -------------------------------- ### Basic Process Creation with multiprocessing.Process Source: https://docs.python.org/3.13/library/multiprocessing.html A simple example of creating and starting a new process to execute a function. The `if __name__ == '__main__'` guard is crucial for proper execution. ```python from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ``` -------------------------------- ### Get Help for Functional penup Source: https://docs.python.org/3.13/library/turtle.html Use Python's help() function to view the docstring for the functional version of penup. This shows its aliases and provides a usage example. ```python >>> help(penup) Help on function penup in module turtle: penup() Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example: >>> penup() ``` -------------------------------- ### Class Setup and Teardown Source: https://docs.python.org/3.13/library/unittest.html Implement setUpClass and tearDownClass as class methods for expensive object creation and destruction within a test class. Ensure to call superclass methods if needed. ```python import unittest class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls._connection = createExpensiveConnectionObject() @classmethod def tearDownClass(cls): cls._connection.destroy() ``` -------------------------------- ### BaseRequestHandler.setup Source: https://docs.python.org/3.13/library/socketserver.html Called before the `handle()` method to perform any initialization actions required. The default implementation does nothing. ```APIDOC ## BaseRequestHandler.setup() ### Description Called before the `handle()` method to perform any initialization actions required. The default implementation does nothing. ### Method (Called by the request handler instance) ### Endpoint N/A ``` -------------------------------- ### Get Number of Mock Object Calls Source: https://docs.python.org/3.13/library/unittest.mock.html The `call_count` attribute returns an integer representing the total number of times the mock object has been called. It starts at 0 and increments with each invocation. ```python >>> mock = Mock(return_value=None) >>> mock.call_count 0 >>> mock() >>> mock() >>> mock.call_count 2 ``` -------------------------------- ### Populate OptionParser with Documented Options Source: https://docs.python.org/3.13/library/optparse.html Define a usage string and add options with help messages, default values, and actions. This setup enables optparse to generate comprehensive help output. ```python usage = "usage: %prog [options] arg1 arg2" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=True, help="make lots of noise [default]") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", help="be vewwy quiet (I'm hunting wabbits)") parser.add_option("-f", "--filename", metavar="FILE", help="write output to FILE") parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: novice, intermediate, " "or expert [default: %default]") ``` -------------------------------- ### Getting Span of Matched Group Source: https://docs.python.org/3.13/library/re.html Demonstrates the span() method, which returns a tuple of the start and end indices for a matched group. Returns (-1, -1) if the group did not contribute to the match. ```python m.start(group), m.end(group) ``` -------------------------------- ### IMAP4 Example Source: https://docs.python.org/3.13/library/imaplib.html A minimal example demonstrating how to open a mailbox, log in, select it, search for all messages, fetch their RFC822 content, print them, and then close and log out. ```APIDOC ## IMAP4 Example ### Description Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages: ### Code ```python import getpass, imaplib M = imaplib.IMAP4(host='example.org') M.login(getpass.getuser(), getpass.getpass()) M.select() typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') print('Message %s\n%s\n' % (num, data[0][1])) M.close() M.logout() ``` ### Note A `FETCH` response may contain additional or unsolicited data (see **RFC 3501**, section 7.4.2), so production code should inspect the whole response rather than rely on `data[0][1]`. ``` -------------------------------- ### Get supported archive formats Source: https://docs.python.org/3.13/library/shutil.html Call `shutil.get_archive_formats()` to retrieve a list of archive formats supported by the current Python installation. Each format is returned as a tuple containing its name and a description. ```python shutil.get_archive_formats() ``` -------------------------------- ### Get Trace Source: https://docs.python.org/3.13/library/inspect.html Returns a list of `FrameInfo` objects for the stack between the current frame and the frame where an exception was raised during exception handling. The list starts with the caller and ends where the exception occurred. ```python inspect.trace(_context =1_) ``` -------------------------------- ### Example Command Line Usage Source: https://docs.python.org/3.13/library/optparse.html Illustrates various ways users can invoke a script that uses optparse, including long and short options, merged short options, and options with or without spaces before their arguments. ```bash --file=outfile -q ``` ```bash -f outfile --quiet ``` ```bash --quiet --file outfile ``` ```bash -q -foutfile ``` ```bash -qfoutfile ``` -------------------------------- ### Get Outer Frames Source: https://docs.python.org/3.13/library/inspect.html Obtains a list of `FrameInfo` objects representing the call stack leading up to a specific frame. The list starts with the given frame and ends with the outermost call. ```python inspect.getouterframes(_frame_ , _context =1_) ```