or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-us

A package for easily working with US and state metadata

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/us@3.2.x

To install, run

npx @tessl/cli install tessl/pypi-us@3.2.0

index.mddocs/

US States and Territories

A Python library providing comprehensive metadata and lookup utilities for US states, territories, and obsolete territories. Includes state names, postal abbreviations, FIPS codes, capitals, time zones, statehood years, and access to Census Bureau shapefiles.

Package Information

  • Package Name: us
  • Language: Python
  • Installation: pip install us

Core Imports

import us
from us import states

Individual state access:

import us
# Access states via us.states.STATE_ABBR
maryland = us.states.MD
california = us.states.CA

National metadata (automatically available):

import us
# National metadata is available directly
print(us.name)      # "United States of America"
print(us.abbr)      # "US"
print(us.birthday)  # datetime.date(1776, 7, 4)

Basic Usage

import us

# Access state collections
print(f"Total states: {len(us.STATES)}")
print(f"Total territories: {len(us.TERRITORIES)}")

# Direct state access by abbreviation
california = us.states.CA
print(f"California capital: {california.capital}")
print(f"FIPS code: {california.fips}")

# Fuzzy state lookup
state = us.states.lookup('maryland')
print(f"Found: {state.name} ({state.abbr})")

# Generate mapping dictionaries
abbr_to_name = us.states.mapping('abbr', 'name')
print(abbr_to_name['CA'])  # 'California'

# Access shapefile URLs
urls = california.shapefile_urls()
if urls:
    print(f"State boundary: {urls['state']}")

Capabilities

State Lookup

Semi-fuzzy state lookup with automatic field detection supporting FIPS codes, abbreviations, and phonetic name matching.

def lookup(val, field: Optional[str] = None, use_cache: bool = True) -> Optional[State]:
    """
    Perform semi-fuzzy state lookup with automatic field detection.
    
    Args:
        val: Lookup value (FIPS code, abbreviation, or name)
        field: Specific field to match against (optional)
        use_cache: Whether to use result caching (default True)
    
    Returns:
        State object if found, None otherwise
    
    Lookup behavior:
        - 2 digits → FIPS code search
        - 2 letters → abbreviation search  
        - Other → phonetic name matching using metaphone
    """

State Mapping

Generate lookup dictionaries between any two state attributes for efficient data transformation.

def mapping(from_field: str, to_field: str, states: Optional[Iterable[State]] = None) -> Dict[Any, Any]:
    """
    Generate lookup dictionary between two state attributes.
    
    Args:
        from_field: Source attribute name (e.g., 'abbr', 'fips', 'name')
        to_field: Target attribute name (e.g., 'name', 'capital', 'fips')
        states: State collection to use (defaults to all states and territories)
    
    Returns:
        Dictionary mapping from_field values to to_field values
    """

State Collections

Pre-defined collections of state objects organized by geographic and political classifications.

STATES: List[State]  # All 50 US states (51 if DC_STATEHOOD environment variable set)
TERRITORIES: List[State]  # US territories (AS, GU, MP, PR, VI)
STATES_AND_TERRITORIES: List[State]  # Combined states and territories (55 normally, 56 with DC_STATEHOOD)
STATES_CONTIGUOUS: List[State]  # Contiguous 48 states (49 with DC_STATEHOOD set)
STATES_CONTINENTAL: List[State]  # Continental states including Alaska (49 normally, 50 with DC_STATEHOOD)
OBSOLETE: List[State]  # Obsolete territories (Dakota, Orleans, Philippine Islands)
COMMONWEALTHS: List[State]  # States calling themselves commonwealths (KY, MA, PA, VA)

Individual State Constants

Direct access to state objects by their postal abbreviations.

# All 50 states available as constants
AL: State  # Alabama
AK: State  # Alaska
AZ: State  # Arizona
AR: State  # Arkansas
CA: State  # California
CO: State  # Colorado
CT: State  # Connecticut
DE: State  # Delaware
FL: State  # Florida
GA: State  # Georgia
HI: State  # Hawaii
ID: State  # Idaho
IL: State  # Illinois
IN: State  # Indiana
IA: State  # Iowa
KS: State  # Kansas
KY: State  # Kentucky
LA: State  # Louisiana
ME: State  # Maine
MD: State  # Maryland
MA: State  # Massachusetts
MI: State  # Michigan
MN: State  # Minnesota
MS: State  # Mississippi
MO: State  # Missouri
MT: State  # Montana
NE: State  # Nebraska
NV: State  # Nevada
NH: State  # New Hampshire
NJ: State  # New Jersey
NM: State  # New Mexico
NY: State  # New York
NC: State  # North Carolina
ND: State  # North Dakota
OH: State  # Ohio
OK: State  # Oklahoma
OR: State  # Oregon
PA: State  # Pennsylvania
RI: State  # Rhode Island
SC: State  # South Carolina
SD: State  # South Dakota
TN: State  # Tennessee
TX: State  # Texas
UT: State  # Utah
VT: State  # Vermont
VA: State  # Virginia
WA: State  # Washington
WV: State  # West Virginia
WI: State  # Wisconsin
WY: State  # Wyoming

# Territories and special cases
AS: State  # American Samoa
GU: State  # Guam
MP: State  # Northern Mariana Islands
PR: State  # Puerto Rico
VI: State  # Virgin Islands
DC: State  # District of Columbia

# Obsolete territories
DK: State  # Dakota Territory
OL: State  # Orleans Territory
PI: State  # Philippine Islands

National Metadata

Constants representing United States national-level information, available directly from the us module.

# Available directly from us module
name: str  # "United States of America"
abbr: str  # "US"
birthday: datetime.date  # July 4, 1776

Version Information

Package version constant.

# From us module
version: str  # Package version (imported from us.version.__version__)

Command Line Interface

CLI tool for quick state information lookup and retrieval.

def main():
    """
    CLI entry point for state information lookup.
    Available as 'states' command after installation.
    """

Types

from typing import Optional, List, Dict, Any
import datetime

class State:
    """
    Represents a US state, territory, or obsolete territory with comprehensive metadata.
    """
    
    abbr: str  # Postal abbreviation (e.g., "MD", "CA")
    ap_abbr: Optional[str]  # Associated Press style abbreviation (e.g., "Md.")
    capital: Optional[str]  # Capital city name
    capital_tz: Optional[str]  # Timezone of the capital city
    fips: Optional[str]  # FIPS code (2-digit string)
    is_territory: bool  # Whether this is a US territory
    is_obsolete: bool  # Whether this is an obsolete territory
    is_contiguous: bool  # Whether geographically contiguous with continental US
    is_continental: bool  # Whether part of continental North America
    name: str  # Full state/territory name
    name_metaphone: str  # Metaphone phonetic encoding of name
    statehood_year: Optional[int]  # Year of statehood (None for territories)
    time_zones: List[str]  # List of timezone identifiers
    
    def __init__(self, **kwargs):
        """Initialize State with keyword arguments."""
    
    def __repr__(self) -> str:
        """Return State representation."""
    
    def __str__(self) -> str:
        """Return State name as string."""
    
    def shapefile_urls(self) -> Optional[Dict[str, str]]:
        """
        Returns Census Bureau shapefile URLs for various geographic regions.
        
        Returns:
            Dictionary with shapefile types as keys and URLs as values:
            - 'block': Census blocks
            - 'blockgroup': Block groups
            - 'tract': Census tracts
            - 'cd': Congressional districts
            - 'county': Counties
            - 'state': State boundaries
            - 'zcta': ZIP Code Tabulation Areas
            
            Returns None if state has no FIPS code.
            All shapefiles are from 2010 US Census TIGER/Line datasets.
        """

Environment Variables

DC_STATEHOOD: Optional[str]

When set to any truthy value before importing the package, includes Washington DC in STATES, STATES_AND_TERRITORIES, STATES_CONTIGUOUS, and STATES_CONTINENTAL collections.

Effect on collection sizes:

  • STATES: 50 → 51
  • STATES_AND_TERRITORIES: 55 → 56
  • STATES_CONTIGUOUS: 48 → 49
  • STATES_CONTINENTAL: 49 → 50

Usage:

# Set environment variable before running Python
export DC_STATEHOOD=1
python -c "import us; print(len(us.STATES))"  # Prints 51

Usage Examples

State Information Retrieval

import us

# Get state by different methods
maryland = us.states.MD
maryland_lookup = us.states.lookup('Maryland')
maryland_fips = us.states.lookup('24', field='fips')

# Access state metadata
print(f"Name: {maryland.name}")
print(f"Capital: {maryland.capital}")
print(f"FIPS: {maryland.fips}")
print(f"Statehood: {maryland.statehood_year}")
print(f"Time zones: {maryland.time_zones}")

# Access national metadata
print(f"Country: {us.name}")
print(f"Abbreviation: {us.abbr}")
print(f"Independence: {us.birthday}")
print(f"Version: {us.version}")

Creating Data Mappings

import us

# Create various lookup mappings
abbr_to_name = us.states.mapping('abbr', 'name')
fips_to_capital = us.states.mapping('fips', 'capital')
name_to_tz = us.states.mapping('name', 'time_zones')

# Use mappings
print(abbr_to_name['TX'])  # 'Texas'
print(fips_to_capital['48'])  # 'Austin'

Working with Collections

import us

# Analyze state collections
print(f"Continental states: {len(us.STATES_CONTINENTAL)}")
print(f"Contiguous states: {len(us.STATES_CONTIGUOUS)}")
print(f"Territories: {len(us.TERRITORIES)}")

# Filter states by criteria
western_states = [s for s in us.STATES if 'Pacific' in s.time_zones]
island_territories = [s for s in us.TERRITORIES if not s.is_continental]

Shapefile Access

import us

# Get shapefile URLs for a state
texas = us.states.TX
shapefiles = texas.shapefile_urls()

# Note: shapefile_urls() returns None for states without FIPS codes
if shapefiles:
    print(f"Counties: {shapefiles['county']}")
    print(f"Congressional districts: {shapefiles['cd']}")
    print(f"Census tracts: {shapefiles['tract']}")
else:
    print("No shapefiles available (no FIPS code)")

Command Line Usage

# Install package provides 'states' command
states md  # Look up Maryland information
states california  # Look up by full name
states 06  # Look up by FIPS code