### Launch Python Interactive Interpreter Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_1.md Demonstrates how to start the Python interactive interpreter and execute a 'Hello World' statement. This is a fundamental step for interactive Python development. ```python >>> print('Hello World') Hello World >>> ``` -------------------------------- ### Execute Python code dynamically with exec() Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex6_4.md Demonstrates how to use exec() to run Python code stored in a string. Shows execution of a simple loop and dynamic creation of class __init__ methods. The example creates an __init__ method based on class field definitions. ```python code = ''' for i in range(n): print(i, end=' ') ''' n = 10 exec(code) ``` ```python class Stock: _fields = ('name', 'shares', 'price') argstr = ','.join(Stock._fields) code = f'def __init__(self, {argstr}):\n' for name in Stock._fields: code += f' self.{name} = {name}\n' print(code) # Output: def __init__(self, name,shares,price): # self.name = name # self.shares = shares # self.price = price locs = { } exec(code, locs) Stock.__init__ = locs['__init__'] # Test the class s = Stock('GOOG', 100, 490.1) print(s.name) # 'GOOG' print(s.shares) # 100 print(s.price) # 490.1 ``` -------------------------------- ### Stock Class Usage Examples in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex6_2.md Demonstrates the instantiation and usage of the Stock class. It shows how to create a Stock object using keyword arguments, access its attributes, and how the help() function provides signature information. This section verifies the class's functionality and introspection capabilities. ```python >>> s = Stock(name='GOOG', price=490.1, shares=50) >>> s.name 'GOOG' >>> s.shares 50 >>> s.price 490.1 >>> help(Stock) ... ``` -------------------------------- ### Example Usage: Reading Stock Portfolio with Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_3.md Demonstrates how to use the `read_csv_as_instances` function to load a list of `Stock` objects from a CSV file. This example requires the `Stock` class to be defined elsewhere and assumes a 'portfolio.csv' file exists. ```python >>> # Read a portfolio of Stock instances >>> from reader import read_csv_as_instances >>> from stock import Stock >>> portfolio = read_csv_as_instances('Data/portfolio.csv', Stock) >>> portfolio [<__main__.Stock object at 0x100674748>, <__main__.Stock object at 0x1006746d8>, <__main__.Stock object at 0x1006747b8>, <__main__.Stock object at 0x100674828>, <__main__.Stock object at 0x100674898>, <__main__.Stock object at 0x100674908>, <__main__.Stock object at 0x100674978>] >>> ``` -------------------------------- ### Usage examples for CSV parsers Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_7.md Shows practical usage of the refactored CSV parser classes, demonstrating both dictionary-based parsing with type conversion and instance-based parsing using the class methods. ```python >>> from reader import DictCSVParser >>> parser = DictCSVParser([str, int, float]) >>> port = parser.parse('Data/portfolio.csv') >>> >>> import reader >>> import stock >>> port = reader.read_csv_as_instances('Data/portfolio.csv', stock.Stock) >>> ``` -------------------------------- ### String Interning Example (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex2_6.md Demonstrates string interning using `sys.intern()` to reuse string objects and reduce memory usage. ```python >>> a = 'hello world' >>> b = 'hello world' >>> a is b False >>> import sys >>> a = sys.intern(a) >>> b = sys.intern(b) >>> a is b True ``` -------------------------------- ### Python Example: Using redirect_stdout for Table Output Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_6.md Demonstrates the usage of the `redirect_stdout` context manager to capture the output of a table printing function into a file named 'out.txt'. It utilizes a hypothetical `tableformat` library to generate and print a table. ```python from tableformat import create_formatter # Assuming portfolio is defined elsewhere and tableformat.print_table exists formatter = create_formatter('text') with redirect_stdout(open('out.txt', 'w')) as file: tableformat.print_table(portfolio, ['name','shares','price'], formatter) file.close() # To verify, you can read the file content: # print(open('out.txt').read()) ``` -------------------------------- ### Python: Basic Numerical Operations Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_2.md Demonstrates fundamental arithmetic operations with integers and floating-point numbers in Python. Includes examples of multiplication, division, and exponentiation. Also highlights differences in integer division between Python 2 and Python 3, and how to achieve Python 3 behavior in Python 2 using `from __future__ import division`. ```python >>> 3 + 4*5 23 >>> 23.45 / 1e-02 2345.0 >>> ``` ```python >>> 7 / 4 # In python 2, this truncates to 1 1.75 >>> 7 // 4 # Truncating division 1 >>> ``` ```python >>> from __future__ import division >>> 7 / 4 1.75 >>> 7 // 4 # Truncating division 1 >>> ``` -------------------------------- ### Implementation of Stock class and portfolio handling in stock.py Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln3_3.md Defines Stock class with type conversion via @classmethod from_row, implements cost/sell methods, and read_portfolio to process CSV data. Requires 'csv' module and external dependencies 'tableformat' and 'reader'. Input: CSV file 'Data/portfolio.csv'. Output: list of Stock objects, then prints formatted table. Note: Includes commented example for generalized reader function. ```python # stock.py class Stock: types = (str, int, float) def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price def cost(self): return self.shares * self.price def sell(self, nshares): self.shares -= nshares @classmethod def from_row(cls, row): values = [func(val) for func, val in zip(cls.types, row)] return cls(*values) def read_portfolio(filename): ''' Read a CSV file of stock data into a list of Stocks ''' import csv portfolio = [] with open(filename) as f: rows = csv.reader(f) headers = next(rows) for row in rows: record = Stock.from_row(row) portfolio.append(record) return portfolio if __name__ == '__main__': import tableformat import reader portfolio = read_portfolio('Data/portfolio.csv') # Generalized version # portfolio = reader.read_csv_as_instances('Data/portfolio.csv', Stock) tableformat.print_table(portfolio, ['name', 'shares', 'price']) ``` -------------------------------- ### Interactive Python Function Call Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_4.md This example shows how to call the `portfolio_cost` function interactively from a Python interpreter. It demonstrates executing the function with different portfolio data files and expecting specific numerical outputs, illustrating the function's ability to return calculated values. ```python >>> portfolio_cost('Data/portfolio.dat') 44671.15 >>> portfolio_cost('Data/portfolio2.dat') 19908.75 >>> ``` -------------------------------- ### Python Attribute Access with Dot Notation Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_2.md Demonstrates basic attribute manipulation in Python using dot notation for operations like getting, setting, and deleting attributes on a Stock object. This shows the three core object system operations in a straightforward way. Requires a Stock class with name, shares, and price attributes; no external dependencies beyond Python standard library. ```python >>> s = Stock('GOOG', 100, 490.1) >>> s.name # get 'GOOG' >>> s.shares = 50 # set >>> del s.shares # delete >>> ``` -------------------------------- ### Python Built-in Map Function Usage Examples Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex5_3.md Demonstration of Python's built-in map() function for functional programming patterns. Shows how to apply transformations to sequences using lambda functions. The first example shows map() returns an iterator (requiring iteration or list() conversion), while the second shows explicit list conversion. These examples illustrate how to use map() within the refactored convert_csv() function to apply row transformations more functionally. ```python >>> nums = [1,2,3,4] >>> squares = map(lambda x: x*x, nums) >>> for n in squares: print(n) 1 4 9 16 ``` ```python >>> squares = list(map(lambda x: x*x, nums)) >>> squares [1, 4, 9, 16] ``` -------------------------------- ### Python Class Method Example: dict.fromkeys Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_3.md Shows a common use case of class methods as alternate constructors, using the built-in `dict.fromkeys()` method as an example. This method creates a new dictionary with keys from an iterable and a specified value. ```python >>> d = dict.fromkeys(['a','b','c'], 0) # class method >>> d {'a': 0, 'c': 0, 'b': 0} >>> ``` -------------------------------- ### Running the Generative Art Program Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_1.md Shows the command-line execution of the 'art.py' script with specified dimensions for rows and columns. This demonstrates how to run a Python script from the terminal. ```bash bash % python3 art.py 10 20 ``` -------------------------------- ### Interact with Python Stock Object Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_5.md This interactive Python session demonstrates how to create an instance of the 'Stock' class, access its attributes (name, shares, price), and call its 'cost' method. It also shows how to format and print stock information. The 'Stock' class must be defined prior to running these commands. ```python >>> s = Stock('GOOG',100,490.10) >>> s.name 'GOOG' >>> s.shares 100 >>> s.price 490.1 >>> s.cost() 49010.0 >>> print('%10s %10d %10.2f' % (s.name, s.shares, s.price)) GOOG 100 490.10 >>> t = Stock('IBM', 50, 91.5) >>> t.cost() 4575.0 >>> ``` -------------------------------- ### Basic Unit Test for Stock Class Creation in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex5_6.md This code defines a unittest class to verify the basic creation of a Stock instance and its attributes. It imports unittest and the stock module, runs a single test checking name, shares, and price. Purpose is to ensure correct initialization; no external dependencies beyond stock.py; input is Stock constructor arguments; output is assertions passing on match. ```python import unittest import stock class TestStock(unittest.TestCase): def test_create(self): s = stock.Stock('GOOG', 100, 490.1) self.assertEqual(s.name, 'GOOG') self.assertEqual(s.shares, 100) self.assertEqual(s.price, 490.1) if __name__ == '__main__': unittest.main() ``` -------------------------------- ### read_csv_as_columns Function Example (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex2_6.md Shows how to use the `read_csv_as_columns` function to read CSV data into a `DataCollection` object and access it as a sequence of dictionaries. ```python >>> data = read_csv_as_columns('Data/ctabus.csv', types=[str, str, str, int]) >>> data <__main__.DataCollection object at 0x102b45048> >>> len(data) 577563 >>> data[0] {'route': '3', 'date': '01/01/2001', 'daytype': 'U', 'rides': 7354} >>> data[1] {'route': '4', 'date': '01/01/2001', 'daytype': 'U', 'rides': 9288} >>> data[2] {'route': '6', 'date': '01/01/2001', 'daytype': 'U', 'rides': 6048} ``` -------------------------------- ### Python: String Immutability Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_2.md Demonstrates that Python strings are immutable objects. Attempting to modify a character within a string results in a `TypeError`, as shown in the example. ```python >>> symbols[0] = 'a' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment >>> ``` -------------------------------- ### Importing and Using Custom Modules in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_6.md Demonstrates importing pcost module to call portfolio_cost function and stock module to instantiate and use Stock class. Requires pcost.py and stock.py in current directory or sys.path. Outputs show calculated costs and stock details; assumes prior exercises for module definitions. ```python >>> import pcost 44671.15 >>> pcost.portfolio_cost('Data/portfolio2.dat') 19908.75 >>> from stock import Stock >>> s = Stock('GOOG', 100, 490.10) >>> s.name 'GOOG' >>> s.cost() 49010.0 >>> ``` ```python >>> import pcost >>> ``` -------------------------------- ### Generative Art Program in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_1.md A Python script 'art.py' that generates random art using specified characters. It takes 'rows' and 'columns' as command-line arguments. Requires the 'sys' and 'random' modules. ```python # art.py import sys import random chars = '|\/' def draw(rows, columns): for r in rows: print(''.join(random.choice(chars) for _ in range(columns))) if __name__ == '__main__': if len(sys.argv) != 3: raise SystemExit("Usage: art.py rows columns") draw(int(sys.argv[1]), int(sys.argv[2])) ``` -------------------------------- ### Python: Monitor Streaming Data Source with a Generator Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln8_1.md This Python code defines a `follow` generator function that monitors a file for new lines. It uses `f.seek()` to start from the end of the file and `time.sleep()` to avoid busy-waiting while checking for updates. ```python # follow.py import os import time def follow(filename): """ Generator that produces a sequence of lines being written at the end of a file. """ with open(filename,'r') as f: f.seek(0,os.SEEK_END) while True: line = f.readline() if line == '': time.sleep(0.1) # Sleep briefly to avoid busy wait continue yield line # Example use if __name__ == '__main__': for line in follow('Data/stocklog.csv'): row = line.split(',') name = row[0].strip('"') price = float(row[1]) change = float(row[4]) if change < 0: print('%10s %10.2f %10.2f' % (name, price, change)) ``` -------------------------------- ### Set up coroutine file follower using Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex8_3.md Demonstrates a coroutine-based file follower that reads new lines from a stock log and sends them to a consumer. Uses a decorator to prime coroutines and defines a simple printer coroutine. Requires the stocksim.py program to be running and the Data/stocklog.csv file. ```python # cofollow.py import os import time # Data source def follow(filename,target): with open(filename,'r') as f: f.seek(0,os.SEEK_END) while True: line = f.readline() if line != '': target.send(line) else: time.sleep(0.1) # Decorator for coroutine functions from functools import wraps def consumer(func): @wraps(func) def start(*args,**kwargs): f = func(*args,**kwargs) f.send(None) return f return start # Sample coroutine @consumer def printer(): while True: item = yield # Receive an item sent to me print(item) # Example use if __name__ == '__main__': follow('Data/stocklog.csv',printer()) ``` -------------------------------- ### Python: String Indexing and Slicing Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_2.md Illustrates how to access individual characters and substrings within a Python string using indexing and slicing. Demonstrates positive, negative indexing, and slicing with start and end points. Note that strings are immutable. ```python >>> symbols = 'AAPL IBM MSFT YHOO SCO' >>> symbols[0] 'A' >>> symbols[1] 'A' >>> symbols[2] 'P' >>> symbols[-1] # Last character 'O' >>> symbols[-2] # 2nd from last character 'C' >>> ``` ```python >>> symbols[:4] 'AAPL' >>> symbols[-3:] 'SCO' >>> symbols[5:8] 'IBM' >>> ``` -------------------------------- ### Python Dictionary Creation and Access Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex1_2.md Introduces Python dictionaries for mapping keys to values. Shows how to create a dictionary, access values using keys, update existing values, add new key-value pairs, and retrieve a list of all keys. ```python >>> prices = { 'IBM': 91.1, 'GOOG': 490.1, 'AAPL':312.23 } >>> ``` ```python >>> prices['IBM'] 91.1 >>> prices['IBM'] = 123.45 >>> prices['HPQ'] = 26.15 >>> prices {'GOOG': 490.1, 'AAPL': 312.23, 'IBM': 123.45, 'HPQ': 26.15} >>> ``` ```python >>> list(prices) ['GOOG', 'AAPL', 'IBM', 'HPQ'] >>> ``` -------------------------------- ### Print formatted portfolio table Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_1.md Implements a function that prints a nicely formatted table of portfolio data including headers. Requires a list of Stock objects with name, shares, and price attributes. ```python def print_portfolio(portfolio): print('%10s %10s %10s' % ('name', 'shares', 'price')) print('%10s %10s %10s' % ('----------', '----------', '----------')) for s in portfolio: print('%10s %10d %10.2f' % (s.name, s.shares, s.price)) ``` -------------------------------- ### Python Validator Usage Example in a Function Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex4_2.md Illustrates using the Integer validator within a function 'add'. It checks both input parameters 'x' and 'y' to ensure they are integers before performing addition. If validation fails, a TypeError is raised, preventing incorrect operations. ```python def add(x, y): Integer.check(x) Integer.check(y) return x + y ``` -------------------------------- ### Module Splitting for Table Formatting (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln9_3.md Shows how to split a module into submodules for better organization, exemplified by a table formatting module. It includes base formatter classes, mixins, and factory functions. ```python # tableformat/formats/text.py from ..formatter import TableFormatter class TextTableFormatter(TableFormatter): ... # tableformat/formats/csv.py from ..formatter import TableFormatter class CSVTableFormatter(TableFormatter): ... # tableformat/formats/html.py from ..formatter import TableFormatter class HTMLTableFormatter(TableFormatter): ... ``` ```python # tableformat/formatter.py from abc import ABC, abstractmethod def print_table(records, fields, formatter): if not isinstance(formatter, TableFormatter): raise RuntimeError('Expected a TableFormatter') formatter.headings(fields) for r in records: rowdata = [getattr(r, fieldname) for fieldname in fields] formatter.row(rowdata) class TableFormatter(ABC): @abstractmethod def headings(self, headers): pass @abstractmethod def row(self, rowdata): pass from .formats.text import TextTableFormatter from .formats.csv import CSVTableFormatter from .formats.html import HTMLTableFormatter class ColumnFormatMixin: formats = [] def row(self, rowdata): rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)] super().row(rowdata) class UpperHeadersMixin: def headings(self, headers): super().headings([h.upper() for h in headers]) def create_formatter(name, column_formats=None, upper_headers=False): if name == 'text': formatter_cls = TextTableFormatter elif name == 'csv': formatter_cls = CSVTableFormatter elif name == 'html': formatter_cls = HTMLTableFormatter else: raise RuntimeError('Unknown format %s' % name) if column_formats: class formatter_cls(ColumnFormatMixin, formatter_cls): formats = column_formats if upper_headers: class formatter_cls(UpperHeadersMixin, formatter_cls): pass return formatter_cls() ``` ```python # tableformat/__init__.py from .formatter import print_table, create_formatter __all__ = [ 'print_table', 'create_formatter' ] ``` -------------------------------- ### Define a dynamic Structure class in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln6_3.md This Python code defines a base class 'Structure' that automatically infers its fields from the __init__ signature. It uses inspect.signature to get parameters and handles attribute setting and representation. Dependencies include the 'sys' and 'inspect' modules. ```python # structure.py import sys import inspect class Structure: _fields = () @staticmethod def _init(): locs = sys._getframe(1).f_locals self = locs.pop('self') for name, val in locs.items(): setattr(self, name, val) def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: raise AttributeError('No attribute %s' % name) def __repr__(self): return '%s(%s)' % (type(self).__name__, ', '.join(repr(getattr(self, name)) for name in self._fields)) @classmethod def set_fields(cls): sig = inspect.signature(cls) cls._fields = tuple(sig.parameters) ``` -------------------------------- ### Apply ColumnFormatMixin to Format Portfolio Data in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_8.md Demonstrates practical usage of ColumnFormatMixin with TextTableFormatter to create a custom formatter for stock portfolio data. Shows how to import required modules, read CSV data into instances, define a formatter class with specific format strings, and print formatted output. Relies on the tableformat, stock, and reader modules. ```python import stock, reader portfolio = reader.read_csv_as_instances('Data/portfolio.csv', stock.Stock) from tableformat import TextTableFormatter, ColumnFormatMixin, print_table class PortfolioFormatter(ColumnFormatMixin, TextTableFormatter): formats = ['%s', '%d', '%0.2f'] formatter = PortfolioFormatter() print_table(portfolio, ['name','shares','price'], formatter) ``` -------------------------------- ### Creating HTML Table Formatter with Factory Function in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_5.md The `create_formatter` function simplifies formatter creation by accepting a format string like 'html' and returning the appropriate instance for table output. It depends on the `tableformat` module with implemented formatter classes and requires `portfolio` data to be defined. Inputs include the format type and table data; outputs are formatted tables. Limitation: Assumes predefined formatters exist in the module and data like `portfolio` is available. ```python from tableformat import create_formatter, print_table formatter = create_formatter('html') print_table(portfolio, ['name','shares','price'], formatter) ``` -------------------------------- ### Python Coroutine with `yield from` for Receiving Typed Messages Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex8_6.md An example coroutine `print_ints` that uses `yield from receive(int)` to delegate the receiving of an integer message. It then prints the received integer. This demonstrates the cleaner syntax and explicit type checking provided by `yield from`. ```python @consumer def print_ints(): while True: val = yield from receive(int) print('Got:', val) ``` -------------------------------- ### Type checking demonstration with table formatter Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_7.md Demonstrates type checking in Python by showing how to check if an object inherits from a base class and the limitations of such checks. The example shows a failed type check when a non-conforming formatter is passed to the table printing function. ```python >>> import stock, reader, tableformat >>> portfolio = reader.read_csv_as_instances('Data/portfolio.csv', stock.Stock) >>> class MyFormatter: def headings(self,headers): pass def row(self,rowdata): pass >>> tableformat.print_table(portfolio, ['name','shares','price'], MyFormatter()) Traceback (most recent call last): ... TypeError: Expected a TableFormatter >>> ``` -------------------------------- ### Define a Simple Python Module (simplemod.py) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex9_1.md Defines a basic Python module named 'simplemod' with a global variable 'x', a function 'foo()', a class 'Spam', and a print statement to indicate when the module is loaded. ```python # simplemod.py x = 42 # A global variable # A simple function def foo(): print('x is', x) # A simple class class Spam: def yow(self): print('Yow!') # A scripting statement print('Loaded simplemod') ``` -------------------------------- ### Python Stock Class: Subclassing with Type Reconcilation using `_types` and Properties Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_4.md Illustrates reconciling type checking between class variables (`_types`) and properties in the `Stock` class. It shows how subclassing can redefine `_types` and how properties should respect these types, using `Decimal` as an example. ```python >>> from decimal import Decimal >>> class DStock(Stock): _types = (str, int, Decimal) >>> s = DStock('AA', 50, Decimal('91.1')) >>> s.price = 92.3 Traceback (most recent call last): ... TypeError: Expected a Decimal >>> ``` -------------------------------- ### Define Stock class with automatic validation via inheritance Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex7_3.md Cleanest implementation relying solely on inheritance from Structure. Automatically gets validation and initialization without decorators or manual method calls. Demonstrates the power of __init_subclass__ for creating intuitive, declarative class definitions. ```python # stock.py from structure import Structure from validate import String, PositiveInteger, PositiveFloat class Stock(Structure): name = String() shares = PositiveInteger() price = PositiveFloat() @property def cost(self): return self.shares * self.price def sell(self, nshares): self.shares -= nshares ``` -------------------------------- ### Export Everything with __all__ and Wildcard Imports (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln9_3.md Demonstrates exporting all symbols from submodules and aggregating them into the main package's __all__ list. This is achieved using wildcard imports and list unpacking. ```python # structly/__init__.py from .structure import * from .reader import * from .tableformat import * __all__ = [ *structure.__all__, *reader.__all__, *tableformat.__all__ ] ``` -------------------------------- ### Implement Stock Subclass in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln6_4.md Demonstrates a Stock class inheriting from Structure with predefined fields and additional methods. Shows usage of the dynamic initialization system with create_init(). ```python from structure import Structure class Stock(Structure): _fields = ('name', 'shares', 'price') @property def cost(self): return self.shares * self.price def sell(self, nshares): self.shares -= nshares Stock.create_init() ``` -------------------------------- ### Demonstrate Python function argument passing with *args and **kwargs Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex6_1.md Shows multiple ways to call functions using positional arguments, keyword arguments, tuple unpacking with *, and dictionary unpacking with **. Demonstrates flexibility in argument passing order and combination of techniques. This technique enables dynamic function invocation with variable argument sources. ```python def foo(x, y, z): return x + y + z foo(1, 2, 3) foo(1, z=3, y=2) args = (1, 2, 3) foo(*args) kwargs = {'y':2, 'z':3 } foo(1,**kwargs) ``` -------------------------------- ### Custom Descriptor Class Implementation (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex4_3.md Defines a basic 'Descriptor' class with '__init__', '__get__', '__set__', and '__delete__' methods. This serves as a foundational example for creating custom descriptors, showing how each method intercepts attribute access, assignment, and deletion, printing messages to indicate their invocation. ```python # descrip.py class Descriptor: def __init__(self, name): self.name = name def __get__(self, instance, cls): print('%s:__get__' % self.name) def __set__(self, instance, value): print('%s:__set__ %s' % (self.name, value)) def __delete__(self, instance): print('%s:__delete__' % self.name) ``` -------------------------------- ### Manual Stock Class Creation using type() Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex7_4.md Demonstrates how to create a class manually by defining methods as separate functions, organizing them in a methods dictionary, and using type() to construct the final class object. This shows the internal mechanics of class creation in Python. ```python class Stock: def __init__(self,name,shares,price): self.name = name self.shares = shares self.price = price def cost(self): return self.shares*self.price def sell(self,nshares): self.shares -= nshares ``` ```python def __init__(self,name,shares,price): self.name = name self.shares = shares self.price = price def cost(self): return self.shares*self.price def sell(self,nshares): self.shares -= nshares ``` ```python methods = { '__init__' : __init__, 'cost' : cost, 'sell' : sell } ``` ```python Stock = type('Stock',(object,),methods) s = Stock('GOOG',100,490.10) s.name 'GOOG' s.cost() 49010.0 s.sell(25) s.shares 75 ``` -------------------------------- ### Counting with Enumerate in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex2_3.md Uses enumerate to add row numbers while iterating over rows, optionally combining with tuple unpacking. No dependencies beyond standard library. Inputs rows list, outputs numbered rows. Limitations: Starts indexing from 0; assumes rows are sequences. ```python >>> for rowno, row in enumerate(rows): print(rowno, row) >>> for rowno, (name, shares, price) in enumerate(rows): print(rowno, name, shares, price) ``` -------------------------------- ### Python Stock Class: Basic Initialization and Attribute Access Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_4.md Demonstrates the basic usage of a `Stock` class, showing how to initialize it with name, shares, and price, and access these attributes directly. This serves as a baseline before applying encapsulation techniques. ```python >>> s = Stock('GOOG',100,490.10) >>> s.name 'GOOG' >>> s.shares 100 >>> s.price 490.1 >>> s.cost() 49010.0 >>> ``` -------------------------------- ### Inspecting Signature of Stock Class Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex6_3.md This snippet uses inspect to get the signature of the Stock class constructor. It requires the inspect module and a Stock class instance. Input is the class type; output is parameter tuple. Limitation: Assumes Stock has a proper __init__ signature defined. ```python >>> import inspect >>> sig = inspect.signature(Stock) >>> tuple(sig.parameters) ('name', 'shares', 'price') >>> ``` -------------------------------- ### Python Bound Methods Access and Calling Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_2.md Explains that methods are attributes that can be looked up via dot notation or getattr, showing bound method objects and their execution. Demonstrates calling methods directly or through getattr(). Requires a Stock class with a 'cost' method that calculates cost based on shares and price. ```python >>> s = Stock('GOOG',100,490.10) >>> s.cost # Looks up the method > >>> s.cost() # Looks up and calls the method 49010.0 >>> # Same operations using getattr() >>> getattr(s, 'cost') > >>> getattr(s, 'cost')() 49010.0 >>> ``` -------------------------------- ### Async/Await with GenSocket Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln8_6.md This code demonstrates asynchronous socket handling using Python's `async` and `await` keywords, along with a custom `GenSocket` class. It showcases how to create an asynchronous TCP server and echo handler for concurrent socket operations. ```python from socket import * from select import select from collections import deque from types import coroutine tasks = deque() recv_wait = {} # sock -> task send_wait = {} # sock -> task def run(): while any([tasks, recv_wait, send_wait]): while not tasks: can_recv, can_send, _ = select(recv_wait, send_wait, []) for s in can_recv: tasks.append(recv_wait.pop(s)) for s in can_send: tasks.append(send_wait.pop(s)) task = tasks.popleft() try: reason, resource = task.send(None) if reason == 'recv': recv_wait[resource] = task elif reason == 'send': send_wait[resource] = task else: raise RuntimeError('Unknown reason %r' % reason) except StopIteration: print('Task done') class GenSocket: def __init__(self, sock): self.sock = sock @coroutine def accept(self): yield 'recv', self.sock client, addr = self.sock.accept() return GenSocket(client), addr @coroutine def recv(self, maxsize): yield 'recv', self.sock return self.sock.recv(maxsize) @coroutine def send(self, data): yield 'send', self.sock return self.sock.send(data) def __getattr__(self, name): return getattr(self.sock, name) async def tcp_server(address, handler): sock = GenSocket(socket(AF_INET, SOCK_STREAM)) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.bind(address) sock.listen(5) while True: client, addr = await sock.accept() tasks.append(handler(client, addr)) async def echo_handler(client, address): print('Connection from', address) while True: data = await client.recv(1000) if not data: break await client.send(b'GOT:' + data) print('Connection closed') if __name__ == '__main__': tasks.append(tcp_server(('',25000), echo_handler)) ``` -------------------------------- ### Running Worker in Thread Without Result Capture in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex5_2.md Launches the worker function in a separate thread using threading module, but does not capture or access the return value. Demonstrates coordination issue where result is lost. Requires threading import; starts execution asynchronously without waiting. ```python >>> import threading >>> t = threading.Thread(target=worker, args=(2, 3)) >>> t.start() About to work >>> Done ``` -------------------------------- ### Example Usage: Reading Bus Ride Data with Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_3.md Illustrates using `read_csv_as_instances` with a custom `Row` class to parse bus rider data from 'ctabus.csv'. The `Row` class defines how each CSV row maps to an object's attributes, including type conversion for `numrides`. ```python >>> class Row: def __init__(self, route, date, daytype, numrides): self.route = route self.date = date self.daytype = daytype self.numrides = numrides @classmethod def from_row(cls, row): return cls(row[0], row[1], row[2], int(row[3])) >>> rides = read_csv_as_instances('Data/ctabus.csv', Row) >>> len(rides) 577563 >>> ``` -------------------------------- ### Python TCP Server with Generator-Based Tasks Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln8_5.md This Python code sets up a TCP server that handles client connections asynchronously using generators as tasks. It listens for incoming connections and echoes received data back to the clients. The `select` module is used to efficiently manage waiting sockets, and a deque manages the active tasks. ```python # server.py from socket import * from select import select from collections import deque tasks = deque() recv_wait = {} # sock -> task send_wait = {} # sock -> task def run(): while any([tasks, recv_wait, send_wait]): while not tasks: can_recv, can_send, _ = select(recv_wait, send_wait, []) for s in can_recv: tasks.append(recv_wait.pop(s)) for s in can_send: tasks.append(send_wait.pop(s)) task = tasks.popleft() try: reason, resource = task.send(None) if reason == 'recv': recv_wait[resource] = task elif reason == 'send': send_wait[resource] = task else: raise RuntimeError('Unknown reason %r' % reason) except StopIteration: print('Task done') def tcp_server(address, handler): sock = socket(AF_INET, SOCK_STREAM) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.bind(address) sock.listen(5) while True: yield 'recv', sock client, addr = sock.accept() tasks.append(handler(client, addr)) def echo_handler(client, address): print('Connection from', address) while True: yield 'recv', client data = client.recv(1000) if not data: break yield 'send', client client.send(b'GOT:' + data) print('Connection closed') if __name__ == '__main__': tasks.append(tcp_server(('',25000), echo_handler)) run() ``` -------------------------------- ### Create Table Formatters with Mixin Options Using create_formatter() in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_8.md Demonstrates the create_formatter() function that simplifies formatter creation by automatically composing mixin classes. Shows two usage patterns: one with column_formats parameter for data formatting and another with upper_headers parameter for header transformation. Handles class composition internally, providing a cleaner API for end users. ```python from tableformat import create_formatter # Example with column formatting formatter = create_formatter('csv', column_formats=['"%s"','%d','%0.2f']) print_table(portfolio, ['name','shares','price'], formatter) # Example with uppercase headers formatter = create_formatter('text', upper_headers=True) print_table(portfolio, ['name','shares','price'], formatter) ``` -------------------------------- ### Restrict Attribute Setting in Python Structure Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln6_1.md Implements the __setattr__ method in the 'Structure' class to restrict attribute assignments. Only attributes starting with '_' or defined in '_fields' can be set, preventing unintended modifications. Dependencies: The base Structure class. Input: Attribute name and value. Output: Attribute set successfully or AttributeError raised. ```python class Structure: ... def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: raise AttributeError('No attribute %s' % name) ``` -------------------------------- ### Implement Text Table Formatter (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_5.md Provides a concrete implementation of `TableFormatter` for plain text output. The `headings` method prints headers and a separator line, while the `row` method prints formatted data for each row. ```python class TextTableFormatter(TableFormatter): def headings(self, headers): print(' '.join('%10s' % h for h in headers)) print(('-'*10 + ' ')*len(headers)) def row(self, rowdata): print(' '.join('%10s' % d for d in rowdata)) ``` -------------------------------- ### Python Stock Class with __init__ Type Conversion Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex3_3.md Presents an alternative design where type conversions are handled directly within the `__init__` method of the `Stock` class. This approach implicitly converts input arguments to `str`, `int`, and `float`. The example contrasts this with the `from_row` class method approach. ```python class Stock: def __init__(self, name, shares, price): self.name = str(name) self.shares = int(shares) self.price = float(price) # Assuming cost() method exists for demonstration def cost(self): return self.shares * self.price ``` -------------------------------- ### Example Usage of Refactored Structly Package Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex9_3.md This Python script demonstrates how to use the refactored 'structly' package, specifically its table formatting and data structure functionalities. It imports necessary components and creates, manipulates, and displays stock data, showing that the module splitting did not break external usage. ```python # stock.py from structly import * class Stock(Structure): name = String() shares = PositiveInteger() price = PositiveFloat() @property def cost(self): return self.shares * self.price def sell(self, nshares): self.shares -= nshares if __name__ == '__main__': portfolio = read_csv_as_instances('Data/portfolio.csv', Stock) formatter = create_formatter('text') print_table(portfolio, ['name','shares','price'], formatter) ``` -------------------------------- ### Python: Read CSV and Print Stock Data in Table Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex7_6.md This snippet demonstrates reading stock data from a CSV file into Stock objects and then displaying this data in a formatted text table. It requires the 'stock', 'reader', and 'tableformat' modules. The output is a list of Stock instances and a text-based table representation of the portfolio. ```python >>> from stock import Stock >>> from reader import read_csv_as_instances >>> portfolio = read_csv_as_instances('Data/portfolio.csv', Stock) >>> portfolio [Stock('AA',100,32.2), Stock('IBM',50,91.1), Stock('CAT',150,83.44), Stock('MSFT',200,51.23), Stock('GE',95,40.37), Stock('MSFT',50,65.1), Stock('IBM',100,70.44)] >>> from tableformat import create_formatter, print_table >>> formatter = create_formatter('text') >>> print_table(portfolio, ['name','shares','price'], formatter) name shares price ---------- ---------- ---------- AA 100 32.2 IBM 50 91.1 CAT 150 83.44 MSFT 200 51.23 GE 95 40.37 MSFT 50 65.1 IBM 100 70.44 >>> ``` -------------------------------- ### Using Custom Descriptor in a Class (Python) Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex4_3.md Illustrates how to use the custom 'Descriptor' class within another class, 'Foo'. By assigning instances of 'Descriptor' to class attributes ('a', 'b', 'c'), this example shows how the descriptor's methods are invoked automatically upon attribute access, assignment, and deletion on instances of 'Foo'. ```python >>> class Foo: a = Descriptor('a') b = Descriptor('b') c = Descriptor('c') >>> f = Foo() >>> f <__main__.Foo object at 0x38e130> >>> f.a a:__get__ >>> f.b b:__get__ >>> f.a = 23 a:__set__ 23 >>> del f.a a:__delete__ >>> ``` -------------------------------- ### Load Portfolio Data from CSV in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex2_3.md This code imports the csv module, opens the portfolio.csv file, reads the headers, and loads the data rows into a list for further processing. It requires the 'Data/portfolio.csv' file to exist. Outputs headers as a list and rows as a list of lists, assuming the CSV has columns for name, shares, and price. Limitations: Assumes valid CSV format and file presence. ```python >>> import csv >>> f = open('Data/portfolio.csv') >>> f_csv = csv.reader(f) >>> headers = next(f_csv) >>> headers ['name', 'shares', 'price'] >>> rows = list(f_csv) >>> from pprint import pprint >>> pprint(rows) [['AA', '100', '32.20'], ['IBM', '50', '91.10'], ['CAT', '150', '83.44'], ['MSFT', '200', '51.23'], ['GE', '95', '40.37'], ['MSFT', '50', '65.10'], ['IBM', '100', '70.44']] ``` -------------------------------- ### Python Function Validation with ValidatedFunction Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/soln6_5.md Implements a `ValidatedFunction` class that wraps a function to perform type validation on its arguments and return value based on annotations. It uses Python's `inspect` module to get the function signature and `__annotations__`. Dependencies include the `inspect` module and a type checking mechanism (assumed to be defined elsewhere, e.g., `Integer.check`). ```python # validate.py from inspect import signature class ValidatedFunction: def __init__(self, func): self.func = func self.signature = signature(func) self.annotations = dict(func.__annotations__) self.retcheck = self.annotations.pop('return', None) def __call__(self, *args, **kwargs): bound = self.signature.bind(*args, **kwargs) for name, val in self.annotations.items(): val.check(bound.arguments[name]) result = self.func(*args, **kwargs) if self.retcheck: self.retcheck.check(result) return result # Examples if __name__ == '__main__': def add(x:Integer, y:Integer) -> Integer: return x + y add = ValidatedFunction(add) ``` -------------------------------- ### Python Basic Function Type Hints Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex5_1.md Illustrates how to add basic type hints to function arguments and return values in Python. This helps in static analysis and improves code readability. No external dependencies are required for this basic usage. ```python def add(x:int, y:int) -> int: return x + y ``` -------------------------------- ### Stock Class with Method Validation Challenge in Python Source: https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex6_5.md Provides a Stock class example where the sell method uses Integer annotation for shares parameter. Wrapping the unbound method with ValidatedFunction causes binding errors when called on instances due to missing self. Illustrates limitations of callable wrappers on instance methods. ```python class Stock: def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price @property def cost(self): return self.shares * self.price def sell(self, nshares:Integer): self.shares -= nshares sell = ValidatedFunction(sell) # Fails ```