or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# US States and Territories

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: us

7

- **Language**: Python

8

- **Installation**: `pip install us`

9

10

## Core Imports

11

12

```python

13

import us

14

from us import states

15

```

16

17

Individual state access:

18

19

```python

20

import us

21

# Access states via us.states.STATE_ABBR

22

maryland = us.states.MD

23

california = us.states.CA

24

```

25

26

National metadata (automatically available):

27

28

```python

29

import us

30

# National metadata is available directly

31

print(us.name) # "United States of America"

32

print(us.abbr) # "US"

33

print(us.birthday) # datetime.date(1776, 7, 4)

34

```

35

36

## Basic Usage

37

38

```python

39

import us

40

41

# Access state collections

42

print(f"Total states: {len(us.STATES)}")

43

print(f"Total territories: {len(us.TERRITORIES)}")

44

45

# Direct state access by abbreviation

46

california = us.states.CA

47

print(f"California capital: {california.capital}")

48

print(f"FIPS code: {california.fips}")

49

50

# Fuzzy state lookup

51

state = us.states.lookup('maryland')

52

print(f"Found: {state.name} ({state.abbr})")

53

54

# Generate mapping dictionaries

55

abbr_to_name = us.states.mapping('abbr', 'name')

56

print(abbr_to_name['CA']) # 'California'

57

58

# Access shapefile URLs

59

urls = california.shapefile_urls()

60

if urls:

61

print(f"State boundary: {urls['state']}")

62

```

63

64

## Capabilities

65

66

### State Lookup

67

68

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

69

70

```python { .api }

71

def lookup(val, field: Optional[str] = None, use_cache: bool = True) -> Optional[State]:

72

"""

73

Perform semi-fuzzy state lookup with automatic field detection.

74

75

Args:

76

val: Lookup value (FIPS code, abbreviation, or name)

77

field: Specific field to match against (optional)

78

use_cache: Whether to use result caching (default True)

79

80

Returns:

81

State object if found, None otherwise

82

83

Lookup behavior:

84

- 2 digits → FIPS code search

85

- 2 letters → abbreviation search

86

- Other → phonetic name matching using metaphone

87

"""

88

```

89

90

### State Mapping

91

92

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

93

94

```python { .api }

95

def mapping(from_field: str, to_field: str, states: Optional[Iterable[State]] = None) -> Dict[Any, Any]:

96

"""

97

Generate lookup dictionary between two state attributes.

98

99

Args:

100

from_field: Source attribute name (e.g., 'abbr', 'fips', 'name')

101

to_field: Target attribute name (e.g., 'name', 'capital', 'fips')

102

states: State collection to use (defaults to all states and territories)

103

104

Returns:

105

Dictionary mapping from_field values to to_field values

106

"""

107

```

108

109

### State Collections

110

111

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

112

113

```python { .api }

114

STATES: List[State] # All 50 US states (51 if DC_STATEHOOD environment variable set)

115

TERRITORIES: List[State] # US territories (AS, GU, MP, PR, VI)

116

STATES_AND_TERRITORIES: List[State] # Combined states and territories (55 normally, 56 with DC_STATEHOOD)

117

STATES_CONTIGUOUS: List[State] # Contiguous 48 states (49 with DC_STATEHOOD set)

118

STATES_CONTINENTAL: List[State] # Continental states including Alaska (49 normally, 50 with DC_STATEHOOD)

119

OBSOLETE: List[State] # Obsolete territories (Dakota, Orleans, Philippine Islands)

120

COMMONWEALTHS: List[State] # States calling themselves commonwealths (KY, MA, PA, VA)

121

```

122

123

### Individual State Constants

124

125

Direct access to state objects by their postal abbreviations.

126

127

```python { .api }

128

# All 50 states available as constants

129

AL: State # Alabama

130

AK: State # Alaska

131

AZ: State # Arizona

132

AR: State # Arkansas

133

CA: State # California

134

CO: State # Colorado

135

CT: State # Connecticut

136

DE: State # Delaware

137

FL: State # Florida

138

GA: State # Georgia

139

HI: State # Hawaii

140

ID: State # Idaho

141

IL: State # Illinois

142

IN: State # Indiana

143

IA: State # Iowa

144

KS: State # Kansas

145

KY: State # Kentucky

146

LA: State # Louisiana

147

ME: State # Maine

148

MD: State # Maryland

149

MA: State # Massachusetts

150

MI: State # Michigan

151

MN: State # Minnesota

152

MS: State # Mississippi

153

MO: State # Missouri

154

MT: State # Montana

155

NE: State # Nebraska

156

NV: State # Nevada

157

NH: State # New Hampshire

158

NJ: State # New Jersey

159

NM: State # New Mexico

160

NY: State # New York

161

NC: State # North Carolina

162

ND: State # North Dakota

163

OH: State # Ohio

164

OK: State # Oklahoma

165

OR: State # Oregon

166

PA: State # Pennsylvania

167

RI: State # Rhode Island

168

SC: State # South Carolina

169

SD: State # South Dakota

170

TN: State # Tennessee

171

TX: State # Texas

172

UT: State # Utah

173

VT: State # Vermont

174

VA: State # Virginia

175

WA: State # Washington

176

WV: State # West Virginia

177

WI: State # Wisconsin

178

WY: State # Wyoming

179

180

# Territories and special cases

181

AS: State # American Samoa

182

GU: State # Guam

183

MP: State # Northern Mariana Islands

184

PR: State # Puerto Rico

185

VI: State # Virgin Islands

186

DC: State # District of Columbia

187

188

# Obsolete territories

189

DK: State # Dakota Territory

190

OL: State # Orleans Territory

191

PI: State # Philippine Islands

192

```

193

194

### National Metadata

195

196

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

197

198

```python { .api }

199

# Available directly from us module

200

name: str # "United States of America"

201

abbr: str # "US"

202

birthday: datetime.date # July 4, 1776

203

```

204

205

### Version Information

206

207

Package version constant.

208

209

```python { .api }

210

# From us module

211

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

212

```

213

214

### Command Line Interface

215

216

CLI tool for quick state information lookup and retrieval.

217

218

```python { .api }

219

def main():

220

"""

221

CLI entry point for state information lookup.

222

Available as 'states' command after installation.

223

"""

224

```

225

226

## Types

227

228

```python { .api }

229

from typing import Optional, List, Dict, Any

230

import datetime

231

232

class State:

233

"""

234

Represents a US state, territory, or obsolete territory with comprehensive metadata.

235

"""

236

237

abbr: str # Postal abbreviation (e.g., "MD", "CA")

238

ap_abbr: Optional[str] # Associated Press style abbreviation (e.g., "Md.")

239

capital: Optional[str] # Capital city name

240

capital_tz: Optional[str] # Timezone of the capital city

241

fips: Optional[str] # FIPS code (2-digit string)

242

is_territory: bool # Whether this is a US territory

243

is_obsolete: bool # Whether this is an obsolete territory

244

is_contiguous: bool # Whether geographically contiguous with continental US

245

is_continental: bool # Whether part of continental North America

246

name: str # Full state/territory name

247

name_metaphone: str # Metaphone phonetic encoding of name

248

statehood_year: Optional[int] # Year of statehood (None for territories)

249

time_zones: List[str] # List of timezone identifiers

250

251

def __init__(self, **kwargs):

252

"""Initialize State with keyword arguments."""

253

254

def __repr__(self) -> str:

255

"""Return State representation."""

256

257

def __str__(self) -> str:

258

"""Return State name as string."""

259

260

def shapefile_urls(self) -> Optional[Dict[str, str]]:

261

"""

262

Returns Census Bureau shapefile URLs for various geographic regions.

263

264

Returns:

265

Dictionary with shapefile types as keys and URLs as values:

266

- 'block': Census blocks

267

- 'blockgroup': Block groups

268

- 'tract': Census tracts

269

- 'cd': Congressional districts

270

- 'county': Counties

271

- 'state': State boundaries

272

- 'zcta': ZIP Code Tabulation Areas

273

274

Returns None if state has no FIPS code.

275

All shapefiles are from 2010 US Census TIGER/Line datasets.

276

"""

277

```

278

279

## Environment Variables

280

281

```python { .api }

282

DC_STATEHOOD: Optional[str]

283

```

284

285

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

286

287

**Effect on collection sizes:**

288

- `STATES`: 50 → 51

289

- `STATES_AND_TERRITORIES`: 55 → 56

290

- `STATES_CONTIGUOUS`: 48 → 49

291

- `STATES_CONTINENTAL`: 49 → 50

292

293

**Usage:**

294

```bash

295

# Set environment variable before running Python

296

export DC_STATEHOOD=1

297

python -c "import us; print(len(us.STATES))" # Prints 51

298

```

299

300

## Usage Examples

301

302

### State Information Retrieval

303

304

```python

305

import us

306

307

# Get state by different methods

308

maryland = us.states.MD

309

maryland_lookup = us.states.lookup('Maryland')

310

maryland_fips = us.states.lookup('24', field='fips')

311

312

# Access state metadata

313

print(f"Name: {maryland.name}")

314

print(f"Capital: {maryland.capital}")

315

print(f"FIPS: {maryland.fips}")

316

print(f"Statehood: {maryland.statehood_year}")

317

print(f"Time zones: {maryland.time_zones}")

318

319

# Access national metadata

320

print(f"Country: {us.name}")

321

print(f"Abbreviation: {us.abbr}")

322

print(f"Independence: {us.birthday}")

323

print(f"Version: {us.version}")

324

```

325

326

### Creating Data Mappings

327

328

```python

329

import us

330

331

# Create various lookup mappings

332

abbr_to_name = us.states.mapping('abbr', 'name')

333

fips_to_capital = us.states.mapping('fips', 'capital')

334

name_to_tz = us.states.mapping('name', 'time_zones')

335

336

# Use mappings

337

print(abbr_to_name['TX']) # 'Texas'

338

print(fips_to_capital['48']) # 'Austin'

339

```

340

341

### Working with Collections

342

343

```python

344

import us

345

346

# Analyze state collections

347

print(f"Continental states: {len(us.STATES_CONTINENTAL)}")

348

print(f"Contiguous states: {len(us.STATES_CONTIGUOUS)}")

349

print(f"Territories: {len(us.TERRITORIES)}")

350

351

# Filter states by criteria

352

western_states = [s for s in us.STATES if 'Pacific' in s.time_zones]

353

island_territories = [s for s in us.TERRITORIES if not s.is_continental]

354

```

355

356

### Shapefile Access

357

358

```python

359

import us

360

361

# Get shapefile URLs for a state

362

texas = us.states.TX

363

shapefiles = texas.shapefile_urls()

364

365

# Note: shapefile_urls() returns None for states without FIPS codes

366

if shapefiles:

367

print(f"Counties: {shapefiles['county']}")

368

print(f"Congressional districts: {shapefiles['cd']}")

369

print(f"Census tracts: {shapefiles['tract']}")

370

else:

371

print("No shapefiles available (no FIPS code)")

372

```

373

374

### Command Line Usage

375

376

```bash

377

# Install package provides 'states' command

378

states md # Look up Maryland information

379

states california # Look up by full name

380

states 06 # Look up by FIPS code

381

```