### Setup libpostal with uv Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Optionally sets up the 'libpostal' library using 'uv'. This is a prerequisite for certain address processing functionalities. ```bash uv run ryandata-address-utils-setup ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Installs project dependencies using the 'uv' package manager. This is a crucial first step before running tests or linting. ```bash uv sync ``` -------------------------------- ### Bash: Development Workflow with 'uv' Commands Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md This Bash script outlines the development setup and execution commands for the RyanData Address Utils project using the 'uv' package manager. It covers cloning the repository, synchronizing dependencies, running tests, and performing code checks and formatting with tools like pytest, ruff, and mypy. Ensure 'uv' is installed and the repository is cloned locally before execution. ```bash git clone https://github.com/Abstract-Data/RyanData-Address-Utils.git cd RyanData-Address-Utils uv sync uv run pytest uv run ruff check src/ uv run mypy src/ uv run ruff format src/ ``` -------------------------------- ### Protocol-based Design for Extensibility in Python Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Illustrates the use of Python's `Protocol` for defining interfaces that implementations satisfy implicitly, promoting loose coupling. This example shows a `ValidatorProtocol` and its potential implementation. ```python from typing import Protocol # Define protocols in protocols.py class ValidatorProtocol(Protocol): def validate(self, address: Address) -> ValidationResult: ... # Implementations satisfy protocols implicitly class ZipCodeValidator: def validate(self, address: Address) -> ValidationResult: # Implementation ``` -------------------------------- ### Install RyanData Address Utils with pip Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md Commands to install the RyanData Address Utils library using 'pip'. The second command shows how to install with pandas extras for DataFrame processing. ```bash pip install git+https://github.com/Abstract-Data/RyanData-Address-Utils.git pip install "ryandata-address-utils[pandas] @ git+https://github.com/Abstract-Data/RyanData-Address-Utils.git" ``` -------------------------------- ### Install RyanData Address Utils with uv Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md Commands to install the RyanData Address Utils library using the 'uv' package manager. The second command shows how to install with pandas extras for DataFrame processing. ```bash uv add git+https://github.com/Abstract-Data/RyanData-Address-Utils.git # with pandas extras uv add "ryandata-address-utils[pandas] @ git+https://github.com/Abstract-Data/RyanData-Address-Utils.git" ``` -------------------------------- ### Basic Address Parsing with AddressService (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md A fundamental usage example demonstrating how to import AddressService, create an instance, and use the parse method to validate and extract information from an address string. It shows how to access parsed address components. ```python from ryandata_address_utils import AddressService service = AddressService() result = service.parse("123 Main St, Austin TX 78749") if result.is_valid: print(result.address.StreetName) # "Main" print(result.address.ZipCode5) # "78749" ``` -------------------------------- ### Install ryandata-address-utils (Bash) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/llms.txt Provides bash commands for installing the ryandata-address-utils package using `uv`. It shows the command for a standard installation and a separate command for installing with pandas support, which includes additional dependencies. ```bash # Using uv (recommended) uv add git+https://github.com/Abstract-Data/RyanData-Address-Utils.git # With pandas support uv add "ryandata-address-utils[pandas] @ git+https://github.com/Abstract-Data/RyanData-Address-Utils.git" ``` -------------------------------- ### Format Code with uv and Ruff Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Formats the code in the 'src/' directory using 'uv' and 'ruff'. This ensures consistent code style across the project. ```bash uv run ruff format src/ ``` -------------------------------- ### Run Tests with uv Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Executes the project's test suite using 'uv' and 'pytest'. This command is used to verify the integrity of the codebase after making changes. ```bash uv run pytest ``` -------------------------------- ### ProcessLog for Tracking Address Transformations in Python Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Demonstrates how to use the `ProcessLog` system, inherited from `RyanDataValidationBase`, to track cleaning and normalization processes applied to address fields. This provides an audit trail for data transformations. ```python # Models inherit from RyanDataValidationBase which provides process_log address.add_cleaning_process( field="StateName", original_value="Texas", new_value="TX", reason="Normalized state name to abbreviation", ) ``` -------------------------------- ### Generate Architecture Diagram using mermaid-cli Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/diagrams.md This snippet demonstrates how to use the mermaid-cli tool to generate image files (e.g., PNG) from Mermaid diagram definitions in a Markdown file. It requires the mermaid-cli to be installed globally via npm. ```bash npm install -g @mermaid-js/mermaid-cli mmdc -i docs/diagrams.md -o docs/architecture.png ``` -------------------------------- ### Lint Code with uv and Ruff Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Performs code linting on the 'src/' directory using 'uv' and 'ruff'. This helps maintain code quality and identify potential issues. ```bash uv run ruff check src/ ``` -------------------------------- ### Python Unit Testing with Pytest and Coverage Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Provides common pytest commands for running tests, including verbose output, coverage reporting, and filtering tests by name. It also specifies the target coverage percentage. ```bash uv run pytest # Run all tests uv run pytest -v # Verbose output uv run pytest --cov=src # With coverage uv run pytest -k "test_parse" # Run specific tests ``` -------------------------------- ### Handle Errors with Custom Exceptions in Python Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt This example demonstrates how to catch and handle specific exceptions like `RyanDataAddressError` and `RyanDataValidationError` when parsing addresses. It also shows how to configure the service to either raise errors or coerce unparseable data into None values. This requires the ryandata-address-utils library. ```python from ryandata_address_utils import parse, AddressService from ryandata_address_utils.models import RyanDataAddressError, RyanDataValidationError service = AddressService() # Handle parsing errors try: result = service.parse_to_dict( "invalid address", validate=True, errors="raise" ) except RyanDataAddressError as e: print(f"Error type: {e.error_type}") print(f"Message: {e.message}") print(f"Context: {e.context}") # Context includes: package name, field, value # Handle validation errors during parsing try: result = parse("123 Main St, Austin ZZ 99999") # Invalid state/ZIP if not result.is_valid: for error in result.validation.errors: print(f"Field: {error.field}") print(f"Error: {error.message}") print(f"Value: {error.value}") except RyanDataAddressError as e: print(f"Validation failed: {e}") # Coerce errors to None values result_dict = service.parse_to_dict( "unparseable garbage", validate=True, errors="coerce" # Returns dict with all None values ) print(result_dict) # {'AddressNumber': None, 'StreetName': None, ...} ``` -------------------------------- ### Type Check Code with uv and Mypy Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Performs static type checking on the 'src/' directory using 'uv' and 'mypy'. This helps catch type-related errors early in the development process. ```bash uv run mypy src/ ``` -------------------------------- ### Pydantic Model Field Definition with Descriptions Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Defines how to structure Pydantic model fields using `Field()` with descriptions and `AliasChoices` for aliased field names. This ensures clarity and flexibility in model definitions. ```python from pydantic import Field, AliasChoices # Use Field() with descriptions for all model fields field_name: str | None = Field( default=None, description="Clear description of the field", validation_alias=AliasChoices("FieldName", "alias"), ) ``` -------------------------------- ### Pandas DataFrame Address Parsing with ryandata-address-utils Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/AGENTS.md Shows how to use the `AddressService` to parse addresses directly from a Pandas DataFrame column. The `parse_dataframe` method adds parsed fields with an optional prefix to the DataFrame. ```python import pandas as pd from ryandata_address_utils.service import AddressService # Assuming df is a pandas DataFrame with an 'address_column' # df = pd.DataFrame({'address_column': ['123 Main St, Anytown, CA 90210']}) service = AddressService() df = service.parse_dataframe(df, "address_column", prefix="addr_") # Returns DataFrame with addr_StreetName, addr_ZipCode, etc. ``` -------------------------------- ### ZIP Code and State Validation Utilities (Python) Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Provides utility functions for validating and retrieving information about US ZIP codes and states. Includes functions to check validity, get city/state/county details for a ZIP code, and normalize state names. Dependencies: `ryandata_address_utils`. ```python from ryandata_address_utils import AddressService, get_zip_info, is_valid_zip, is_valid_state, normalize_state service = AddressService() # Validate ZIP code print(is_valid_zip("78749")) # True print(is_valid_zip("99999")) # False # Lookup ZIP code information zip_info = get_zip_info("78749") if zip_info: print(f"City: {zip_info.city}") # "Austin" print(f"State: {zip_info.state_id}") # "TX" print(f"County: {zip_info.county}") # Get city and state from ZIP city, state = service.get_city_state_from_zip("78749") print(f"{city}, {state}") # "Austin, TX" # Validate and normalize state print(is_valid_state("TX")) # True print(is_valid_state("Texas")) # True print(is_valid_state("ZZ")) # False print(normalize_state("Texas")) # "TX" print(normalize_state("tx")) # "TX" print(normalize_state("California")) # "CA" ``` -------------------------------- ### Facade Pattern: Initialize and Use AddressService (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Demonstrates the Facade pattern by initializing AddressService and using its parse method to process an address string. This simplifies interaction with the underlying complex system. ```python service = AddressService() result = service.parse("123 Main St, Austin TX 78749") ``` -------------------------------- ### Programmatic Address Building in Python Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md Shows how to construct an address object programmatically using the `AddressBuilder` API. This allows for step-by-step specification of address components. ```python from ryandata_address_utils import AddressBuilder address = ( AddressBuilder() .with_street_number("123") .with_street_name("Main") .with_street_type("St") .with_city("Austin") .with_state("TX") .with_zip("78749") .build() ) ``` -------------------------------- ### Basic Address Parsing in Python Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md Demonstrates how to use the `parse` function to parse a US address string and access its validation status and components. It also shows how to retrieve the full address as a dictionary. ```python from ryandata_address_utils import AddressService, parse result = parse("123 Main St, Austin TX 78749") if result.is_valid: print(result.address.ZipCode) # "78749" print(result.to_dict()) # full address dict else: print(result.validation.errors) # custom errors with context service = AddressService() service.parse("456 Oak Ave, Dallas TX 75201") ``` -------------------------------- ### Tracking Address Transformations in Python Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md Demonstrates how to use `AddressService` to parse an address and implicitly track the transformations applied during the parsing process. The result object would contain information about these transformations if the service is configured to log them. ```python from ryandata_address_utils import AddressService service = AddressService() result = service.parse("123 main st, austin texas 78749") # The 'result' object would contain transformation details if logging is enabled. ``` -------------------------------- ### Strategy Pattern: Inject Custom Parser into AddressService (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Illustrates the Strategy pattern by allowing a custom parser implementation to be passed to AddressService. This enables interchangeable parsing strategies without modifying the service itself. ```python # Any class implementing AddressParserProtocol can be used service = AddressService(parser=CustomParser()) ``` -------------------------------- ### Factory Pattern: Register and Create Parsers with PluginFactory (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Shows the Factory pattern for creating components. Custom parsers can be registered with ParserFactory and then created by their registered name, promoting extensibility. ```python # Register custom implementations ParserFactory.register("custom", CustomParser) parser = ParserFactory.create("custom") ``` -------------------------------- ### Address Parsing with Transformation Tracking (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Shows how to parse an address and access transformation logs. This feature helps in understanding how the input address was normalized and processed, useful for debugging or auditing. ```python result = service.parse("123 main st, austin texas 78749") # See what was normalized for entry in result.aggregate_logs(): print(f"{entry['field']}: {entry['message']}") # state: State name normalized from full name to abbreviation ``` -------------------------------- ### Customizing AddressService with Custom Validators (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Shows how to create and inject a custom `CompositeValidator` into `AddressService`. This allows for tailored validation logic, such as adding specific state-zip code matching. ```python from ryandata_address_utils import AddressService, CompositeValidator # Create custom validation chain validator = CompositeValidator([ ZipCodeValidator(data_source, check_state_match=True), StateValidator(data_source), # Add your own validators here ]) service = AddressService(validator=validator) ``` -------------------------------- ### Programmatic Address Building with AddressBuilder Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Builds complete addresses programmatically using the fluent AddressBuilder interface. Supports various components like street numbers, names, units, PO boxes, and directionals. ```python from ryandata_address_utils import AddressBuilder # Build complete address with all components address = ( AddressBuilder() .with_street_number("123") .with_street_name("Main") .with_street_type("St") .with_unit_type("Apt") .with_unit_number("4B") .with_city("Austin") .with_state("TX") .with_zip("78749") .build() ) print(address.Address1) # "123 Main St" print(address.Address2) # "Apt 4B" print(address.FullAddress) # "123 Main St, Apt 4B, Austin TX 78749" # Build with directionals and modifiers address = ( AddressBuilder() .with_street_number("100") .with_street_pre_directional("N") .with_street_name("Main") .with_street_type("St") .with_street_post_directional("SE") .with_city("Washington") .with_state("DC") .with_zip("20001") .build() ) print(address.FullAddress) # "100 N Main St SE, Washington DC 20001" # Build PO Box address address = ( AddressBuilder() .with_po_box_type("PO Box") .with_po_box_id("1234") .with_city("Austin") .with_state("TX") .with_zip("78749") .build() ) print(address.Address1) # "PO Box 1234" ``` -------------------------------- ### Builder Pattern: Programmatically Construct an Address (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Implements the Builder pattern using a fluent interface for constructing Address objects step-by-step. This provides a readable and maintainable way to build complex objects. ```python address = ( AddressBuilder() .with_street_number("123") .with_street_name("Main") .with_city("Austin") .with_state("TX") .with_zip("78749") .build() ) ``` -------------------------------- ### Directly Use Pydantic Models for Address Data in Python Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt This snippet illustrates how to interact directly with Pydantic models (`Address`, `ParseResult`) provided by the ryandata-address-utils library. It covers creating, validating, serializing, and deserializing address data, as well as accessing parsing and validation details. The `ryandata-address-utils` library and its Pydantic dependencies are required. ```python from ryandata_address_utils.models import Address, ParseResult import json # Create Address model directly address = Address.model_validate({ "AddressNumber": "123", "StreetName": "Main", "StreetNamePostType": "St", "PlaceName": "Austin", "StateName": "TX", "ZipCode": "78749" }) print(address.FullAddress) # Auto-computed: "123 Main St, Austin TX 78749" # Serialize to JSON json_str = address.model_dump_json(exclude_none=True) print(json_str) # Deserialize from JSON address_data = json.loads(json_str) address2 = Address.model_validate(address_data) # Access ParseResult components from ryandata_address_utils import parse result = parse("123 Main St, Austin TX 78749") print(f"Is valid: {result.is_valid}") print(f"Is parsed: {result.is_parsed}") print(f"Source: {result.source}") # "us" or "international" print(f"Raw input: {result.raw_input}") # Export to dictionary addr_dict = result.to_dict() print(addr_dict.keys()) # All 26+ address fields # Access validation details if not result.is_valid: validation = result.validation print(f"Valid: {validation.is_valid}") for error in validation.errors: print(f"- {error.field}: {error.message}") ``` -------------------------------- ### Pandas DataFrame Address Parsing in Python Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md Illustrates how to parse addresses within a pandas DataFrame using `AddressService.parse_dataframe`. It shows how to specify the column containing addresses and add a prefix to the new parsed address columns. ```python import pandas as pd from ryandata_address_utils import AddressService df = pd.DataFrame({"address": ["123 Main St, Austin TX 78749", "456 Oak Ave, Dallas TX 75201"]}) service = AddressService() parsed = service.parse_dataframe(df, "address", prefix="addr_") print(parsed[["addr_AddressNumber", "addr_StreetName", "addr_ZipCode"]]) ``` -------------------------------- ### Implement Custom Validator and Data Source in Python Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt This snippet shows how to create a custom validator to enforce capitalization rules for city names and a custom data source to provide ZIP code information. These custom components can be integrated with the AddressService for tailored address processing. It requires the ryandata-address-utils library. ```python from ryandata_address_utils import AddressService, BaseValidator, BaseDataSource from ryandata_address_utils.models import Address, ZipInfo from ryandata_address_utils.core import ValidationResult, ValidationError # Custom validator implementation class CustomValidator(BaseValidator): """Validate that city names are capitalized.""" def validate(self, address: Address) -> ValidationResult: errors = [] if address.PlaceName and not address.PlaceName[0].isupper(): errors.append( ValidationError( field="PlaceName", message="City name must be capitalized", value=address.PlaceName ) ) return ValidationResult( is_valid=len(errors) == 0, errors=errors ) # Custom data source implementation class CustomDataSource(BaseDataSource): """Custom ZIP code data source.""" def __init__(self, zip_data: dict[str, tuple[str, str]]): self._zip_data = zip_data # {zip: (city, state)} def get_zip_info(self, zip_code: str) -> ZipInfo | None: zip5 = zip_code[:5] data = self._zip_data.get(zip5) if data: city, state = data return ZipInfo(zip=zip5, city=city, state_id=state, state_name=state) return None def is_valid_zip(self, zip_code: str) -> bool: return zip_code[:5] in self._zip_data def is_valid_state(self, state: str) -> bool: return state in {"TX", "CA", "NY"} def normalize_state(self, state: str) -> str | None: mapping = {"texas": "TX", "california": "CA", "new york": "NY"} return mapping.get(state.lower(), state if len(state) == 2 else None) def get_valid_state_abbrevs(self) -> set[str]: return {"TX", "CA", "NY"} # Use custom components custom_data = CustomDataSource({ "78749": ("Austin", "TX"), "90210": ("Beverly Hills", "CA") }) service = AddressService( data_source=custom_data, validator=CustomValidator() ) result = service.parse("123 main st, austin TX 78749") if not result.is_valid: for error in result.validation.errors: print(f"{error.field}: {error.message}") ``` -------------------------------- ### Python: Aggregate Logs from Parsing and Model Transformations Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/README.md This Python snippet demonstrates how to iterate through aggregated logs generated during parsing and model transformations. It prints the field and message for each log entry, providing insights into the transformation process. No external dependencies are explicitly mentioned beyond the assumed `result.aggregate_logs()` method. ```python for entry in result.aggregate_logs(): print(f"{entry['field']}: {entry['message']}") ``` -------------------------------- ### Composite Pattern: Combine Validators into a CompositeValidator (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Demonstrates the Composite pattern by creating a CompositeValidator that holds a list of individual validators (e.g., ZipCodeValidator, StateValidator). These can be run as a single unit. ```python validator = CompositeValidator([ ZipCodeValidator(data_source), StateValidator(data_source), ]) ``` -------------------------------- ### Pandas DataFrame Integration for Address Parsing (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/docs/ARCHITECTURE.md Demonstrates how to integrate AddressService with pandas DataFrames. The `parse_dataframe` method efficiently processes addresses stored in a DataFrame column. ```python import pandas as pd from ryandata_address_utils import AddressService df = pd.DataFrame({"address": ["123 Main St, Austin TX 78749"]}) service = AddressService() result_df = service.parse_dataframe(df, "address") ``` -------------------------------- ### Address Transformation Tracking and Audit Logs Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Tracks address transformations and normalizations performed during parsing for data pipeline auditing. Provides access to detailed logs of each operation. ```python from ryandata_address_utils import AddressService, parse_auto service = AddressService() # Parse address with transformations result = service.parse("123 main st, austin texas 78749") if result.is_valid: # Access transformation logs for entry in result.aggregate_logs(): print(f"Field: {entry['field']}") print(f"Operation: {entry['operation_type']}") print(f"Message: {entry['message']}") print(f"Original: {entry.get('original_value')}") print(f"New: {entry.get('new_value')}") print("---") # Example output: # Field: StateName # Operation: normalization # Message: Normalized state name from full name to abbreviation # Original: texas # New: TX # Track cleaning operations with partial validation result = parse_auto( "123 Main St, Austin TX 78749-99", allow_partial=True ) # Check cleaned and invalid components print(f"Cleaned components: {result.cleaned_components}") # {'street': '123 Main St', 'city': 'Austin', 'state': 'TX', 'zip5': '78749'} print(f"Invalid components: {result.invalid_components}") # {'zip4': {'original_value': '99', 'error': 'Invalid zip4 format'}} # Export audit trail for DataFrame analysis audit_entries = result.aggregate_logs() # Can be converted to DataFrame for batch analysis ``` -------------------------------- ### International and US Address Parsing with Fallback Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Parses addresses automatically, attempting US format first and falling back to libpostal for international addresses. It also supports forcing US-only or international parsing. ```python from ryandata_address_utils import parse_auto, AddressService service = AddressService() # Auto-detect: tries US first, falls back to libpostal for international result = parse_auto("10 Downing Street, London SW1A 2AA, United Kingdom") if result.is_international: print(f"Source: {result.source}") # "international" intl = result.international_address print(f"Road: {intl.Road}") # "Downing Street" print(f"City: {intl.City}") # "London" print(f"Postal Code: {intl.PostalCode}") # "SW1A 2AA" print(f"Country: {intl.Country}") # "United Kingdom" print(f"Full: {intl.FullAddress}") else: # Parsed as US address print(f"US Address: {result.address.FullAddress}") # Force US-only parsing (no libpostal fallback) us_result = service.parse_us_only("123 Main St, Austin TX 78749") # Force international parsing (libpostal only) intl_result = service.parse_international("Rue de Rivoli, 75001 Paris, France") if intl_result.is_valid: print(intl_result.international_address.City) # "Paris" print(intl_result.international_address.PostalCode) # "75001" # Auto-parse with partial validation (cleans invalid optional components) result = parse_auto( "123 Main St, Austin TX 78749-INVALID", validate=True, allow_partial=True # Removes invalid ZIP+4, keeps address valid ) if result.is_valid: print(f"Cleaned: {result.address.FullAddress}") print(f"Invalid components: {result.invalid_components}") ``` -------------------------------- ### Advanced Address Parsing with AddressService (Python) Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Utilizes the `AddressService` class for advanced address processing, including batch operations, custom configurations, and handling of subaddresses and extended ZIP codes. Supports parsing to dictionaries with configurable error handling. Dependencies: `ryandata_address_utils`. ```python from ryandata_address_utils import AddressService # Initialize service (singleton pattern available via get_default_service()) service = AddressService() # Parse single address result = service.parse("123 Main St, Unit 11, Austin TX 78749-1234") if result.is_valid: print(result.address.SubaddressIdentifier) # "11" print(result.address.ZipCode5) # "78749" print(result.address.ZipCode4) # "1234" # Parse batch of addresses addresses = [ "123 Main St, Austin TX 78749", "456 Oak Ave, Dallas TX 75201", "789 Elm St, Houston TX 77001" ] results = service.parse_batch(addresses, validate=True) for result in results: if result.is_valid: print(f"{result.address.PlaceName}: {result.address.FullAddress}") else: print(f"Error: {result.error}") # Parse to dictionary with error handling try: addr_dict = service.parse_to_dict( "123 Main St, Austin TX 78749", validate=True, errors="raise" # or "coerce" for None values on failure ) print(addr_dict["StreetName"]) except Exception as e: print(f"Parsing failed: {e}") ``` -------------------------------- ### Validate ZIP Codes (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/llms.txt Demonstrates how to validate US ZIP codes using `is_valid_zip` and retrieve associated information (city, state, county) using `get_zip_info`. These functions are useful for standalone ZIP code validation without parsing a full address. ```python from ryandata_address_utils import is_valid_zip, get_zip_info is_valid_zip("78749") # True info = get_zip_info("78749") # ZipInfo with city, state, county ``` -------------------------------- ### Build Address Programmatically (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/llms.txt Illustrates the use of the `AddressBuilder` class, which provides a fluent API for constructing `Address` objects programmatically. This method is helpful when creating addresses dynamically or from structured data sources. ```python from ryandata_address_utils import AddressBuilder address = ( AddressBuilder() .with_street_number("123") .with_street_name("Main") .with_city("Austin") .with_state("TX") .with_zip("78749") .build() ) ``` -------------------------------- ### Parse US Address String with Validation (Python) Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Parses a US address string into structured components using the `parse` function. Includes optional validation, returning a result object with address components or validation errors. Dependencies: `ryandata_address_utils`. ```python from ryandata_address_utils import parse # Parse with validation (default) result = parse("123 Main St, Austin TX 78749") if result.is_valid: address = result.address print(f"Street: {address.StreetName}") # "Main" print(f"Number: {address.AddressNumber}") # "123" print(f"City: {address.PlaceName}") # "Austin" print(f"State: {address.StateName}") # "TX" print(f"ZIP: {address.ZipCode}") # "78749" print(f"Full: {address.FullAddress}") # Output: "123 Main St, Austin TX 78749" else: print(f"Validation errors: {result.validation.errors}") # Errors include field name, message, and invalid value # Parse without validation result = parse("456 Oak Ave, Dallas TX 75201", validate=False) print(result.to_dict()) # Returns dict with all 26+ address field components ``` -------------------------------- ### Parse Address with Auto Detection (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/llms.txt Shows how to use the `AddressService.parse_auto` method, which automatically detects whether an address is US-based or international and applies the appropriate parsing logic. This is useful for handling diverse address formats. ```python from ryandata_address_utils import AddressService service = AddressService() result = service.parse_auto("10 Downing Street, London, UK") ``` -------------------------------- ### Parse Single Address (Python) Source: https://github.com/abstract-data/ryandata-address-utils/blob/main/llms.txt Demonstrates the basic usage of the `parse` function to convert a single address string into a structured `ParseResult` object. It validates the address and extracts various components. The `result.is_valid` attribute indicates successful parsing and validation. ```python from ryandata_address_utils import AddressService, parse # Simple parsing result = parse("123 Main St, Austin TX 78749") if result.is_valid: print(result.address.ZipCode) # "78749" # Service-based parsing service = AddressService() result = service.parse("456 Oak Ave, Dallas TX 75201") ``` -------------------------------- ### Pandas DataFrame Address Parsing (Python) Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Integrates with pandas to parse addresses directly within DataFrames. The `parse_dataframe` method expands parsed address components into new columns, with options for prefixes, error handling, and in-place modification. Dependencies: `pandas`, `ryandata_address_utils`. ```python import pandas as pd from ryandata_address_utils import AddressService # Create DataFrame with addresses df = pd.DataFrame({ "id": [1, 2, 3], "address": [ "123 Main St, Austin TX 78749", "456 Oak Ave, Suite 200, Dallas TX 75201", "789 Elm St, Houston TX 77001" ] }) service = AddressService() # Parse addresses and add columns with prefix result_df = service.parse_dataframe( df, "address", validate=True, errors="coerce", # None for invalid addresses prefix="addr_", inplace=False # Returns new DataFrame ) # Access parsed components print(result_df[["id", "addr_StreetName", "addr_PlaceName", "addr_StateName", "addr_ZipCode"]]) # Output: ``` -------------------------------- ### Parse DataFrame with Validation Source: https://context7.com/abstract-data/ryandata-address-utils/llms.txt Parses a Pandas DataFrame containing addresses, with options for validation and error handling. It can raise exceptions for invalid addresses. ```python from ryandata_address_utils import AddressService # Assuming df is a pandas DataFrame with address columns # df = pd.DataFrame(...) service = AddressService() # Use with validation errors raised try: parsed_df = service.parse_dataframe( df, "address", validate=True, errors="raise" ) except Exception as e: print(f"Validation failed: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.