### Sample run of find_path Source: https://www.python.org/doc/essays/graphs Interactive Python session showing the output of find_path(graph, 'A', 'D') using the example graph. ```python >>> find_path(graph, 'A', 'D') ['A', 'B', 'C', 'D'] >>> ``` -------------------------------- ### Integer for-loop example using range Source: https://www.python.org/doc/essays/pepparade Shows the traditional for loop with range(10) that PEP 284 aims to replace. ```python for i in range(10): ``` -------------------------------- ### Tracing metaclass example Source: https://www.python.org/doc/essays/metaclasses A complete simplified example of a metaclass that automatically inserts trace calls for all method calls. It defines the Tracing metaclass, the Instance class, and the BoundMethod class, then creates a class MyTracedClass and demonstrates tracing on method calls. ```python import types class Tracing: def __init__(self, name, bases, namespace): """Create a new class.""" self.__name__ = name self.__bases__ = bases self.__namespace__ = namespace def __call__(self): """Create a new instance.""" return Instance(self) class Instance: def __init__(self, klass): self.__klass__ = klass def __getattr__(self, name): try: value = self.__klass__.__namespace__[name] except KeyError: raise AttributeError, name if type(value) is not types.FunctionType: return value return BoundMethod(value, self) class BoundMethod: def __init__(self, function, instance): self.function = function self.instance = instance def __call__(self, *args): print "calling", self.function, "for", self.instance, "with", args return apply(self.function, (self.instance,) + args) Trace = Tracing('Trace', (), {}) class MyTracedClass(Trace): def method1(self, a): self.a = a def method2(self): return self.a aninstance = MyTracedClass() aninstance.method1(10) print "the answer is %d" % aninstance.method2() ``` -------------------------------- ### Define __all__ in Sounds/Effects/__init__.py Source: https://www.python.org/doc/essays/packages Defines the list of module names to be imported when 'from Sound.Effects import *' is used. This example imports the three named submodules. ```python __all__ = ["echo", "surround", "reverse"] ``` -------------------------------- ### Example usage of iterindexed with start and stop arguments Source: https://www.python.org/doc/essays/pepparade Shows a hypothetical call to iterindexed with start=5 and stop=10, printing indices 5 through 9. The author notes this would be confusing because the spec would print the first five characters, not the range. ```python for i, j in iterindexed("abcdefghij", 5, 10): print i, j ``` -------------------------------- ### Proposed iterindexed implementation with start and stop Source: https://www.python.org/doc/essays/pepparade A proposed implementation of iterindexed that accepts start and stop arguments, iterating over sequence indices and yielding (i, item) pairs. The author suggests this reduces validity to sequences only but makes iterindexed(x, i, j) iterate over x[i:j]. ```python def iterindexed(sequence, start=0, stop=None): i = start while stop is None or i < stop: try: item = sequence[i] except IndexError: break yield (i, item) i += 1 ``` -------------------------------- ### Enum metaclass example: defining enumerated types with class syntax Source: https://www.python.org/doc/essays/metaclasses This example defines an enumerated type using a metaclass called Enum. The class attributes are the enumerated values, and instances are never created. Accessing an attribute like Color.red returns a string representation, equality with the integer value works, and arithmetic operations raise a TypeError. ```python class Color(Enum): red = 1 green = 2 blue = 3 print Color.red ``` -------------------------------- ### Create instances of MySpecialClass and print their class Source: https://www.python.org/doc/essays/metaclasses Creates two instances of MySpecialClass and prints their __class__ attribute, which shows they are instances of HelperClass1. ```python x = MySpecialClass() y = MySpecialClass() print x.__class__, y.__class__ ``` -------------------------------- ### Package directory structure for sound handling Source: https://www.python.org/doc/essays/packages Shows the hierarchical filesystem layout of the Sound package with subpackages Utils, Formats, Effects, and Filters, each containing __init__.py and module files. ```text Sound/ Top-level package __init__.py Initialize the sound package Utils/ Subpackage for internal use __init__.py iobuffer.py errors.py ... Formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... Effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... Filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py dolby.py ... ``` -------------------------------- ### Directory structure for platform-specific effects Source: https://www.python.org/doc/essays/packages Shows the directory layout for a package with platform-specific submodules. The Effects/__init__.py can manipulate __path__ to prioritize platform-specific implementations. ```text Sound/ __init__.py Effects/ # Generic versions of effects modules __init__.py echo.py surround.py reverse.py ... plat-ix86/ # Intel x86 specific effects modules echo.py surround.py plat-PPC/ # PPC specific effects modules echo.py ``` -------------------------------- ### Variable lower bound in integer for-loop Source: https://www.python.org/doc/essays/pepparade An example with a variable lower bound, showing potential confusion with tuple unpacking syntax. ```python for i <= j < k: ``` -------------------------------- ### Import echo with from Sound.Effects import echo Source: https://www.python.org/doc/essays/packages Loads the submodule echo and makes it available without the package prefix, so it can be used as echo.echofilter(input, output, delay=0.7, atten=4). ```python from Sound.Effects import echo ``` -------------------------------- ### Graph arc list Source: https://www.python.org/doc/essays/graphs A textual representation of a directed graph with six nodes (A-F) and eight arcs, used as the example graph throughout the essay. ```text A -> B A -> C B -> C B -> D C -> D D -> C E -> F F -> C ``` -------------------------------- ### f6: Using string.joinfields and map for speed Source: https://www.python.org/doc/essays/list2str The fastest version, using implied loops and C-implemented string concatenation. Runs four to five times faster than f3 and avoids quadratic behavior. ```python import string def f6(list): return string.joinfields(map(chr, list), "") ``` -------------------------------- ### Extracting message and info from SyntaxError Source: https://www.python.org/doc/essays/stdexceptions The same approach works for SyntaxError, but the info part is not always present. The example uses a nested try to handle missing info. ```python try: c = compile(source, filename, "exec") except SyntaxError, what: try: message, info = what except: message, info = what, None if info: "...print source code info..." print "SyntaxError:", msg ```