or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

as-you-type-formatting.mdcore-parsing-formatting.mdindex.mdnumber-validation.mdphone-number-matching.mdregion-metadata.mdshort-numbers.mdutility-functions.md

region-metadata.mddocs/

0

# Region and Metadata

1

2

Functions for working with country codes, region codes, and geographical information. These functions provide access to supported regions, calling codes, number type information, and regional numbering plan data.

3

4

## Capabilities

5

6

### Country Code Operations

7

8

Work with country calling codes and their relationships to geographic regions.

9

10

```python { .api }

11

def country_code_for_region(region_code: str) -> int:

12

"""

13

Get the country calling code for a region.

14

15

Parameters:

16

- region_code: Two-letter region code (ISO 3166-1 alpha-2)

17

18

Returns:

19

Country calling code as integer, or 0 if region not supported

20

"""

21

22

def country_code_for_valid_region(region_code: str) -> int:

23

"""

24

Get country calling code for a region, raising exception if invalid.

25

26

Parameters:

27

- region_code: Two-letter region code

28

29

Returns:

30

Country calling code as integer

31

32

Raises:

33

Exception if region code is not supported

34

"""

35

```

36

37

**Usage Examples:**

38

39

```python

40

import phonenumbers

41

42

# Get country codes for regions

43

us_code = phonenumbers.country_code_for_region("US")

44

print(f"US country code: +{us_code}") # +1

45

46

uk_code = phonenumbers.country_code_for_region("GB")

47

print(f"UK country code: +{uk_code}") # +44

48

49

# Handle invalid regions

50

invalid_code = phonenumbers.country_code_for_region("XX")

51

print(f"Invalid region code: {invalid_code}") # 0

52

```

53

54

### Region Code Lookup

55

56

Determine which regions are associated with specific country calling codes.

57

58

```python { .api }

59

def region_code_for_country_code(country_calling_code: int) -> str:

60

"""

61

Get the main region code for a country calling code.

62

63

For country codes shared by multiple regions, returns the main region.

64

65

Parameters:

66

- country_calling_code: Country calling code to look up

67

68

Returns:

69

Two-letter region code, or 'ZZ' if not found

70

"""

71

72

def region_codes_for_country_code(country_calling_code: int) -> list:

73

"""

74

Get all region codes that use a specific country calling code.

75

76

Parameters:

77

- country_calling_code: Country calling code to look up

78

79

Returns:

80

List of two-letter region codes, empty if none found

81

"""

82

83

def region_code_for_number(numobj: PhoneNumber) -> str:

84

"""

85

Get the region code for a specific phone number.

86

87

Parameters:

88

- numobj: PhoneNumber object to analyze

89

90

Returns:

91

Two-letter region code, or None if cannot be determined

92

"""

93

```

94

95

**Usage Examples:**

96

97

```python

98

import phonenumbers

99

100

# Single region for country code

101

main_region = phonenumbers.region_code_for_country_code(44)

102

print(f"Main region for +44: {main_region}") # GB

103

104

# Multiple regions sharing a country code

105

nanpa_regions = phonenumbers.region_codes_for_country_code(1)

106

print(f"NANPA regions: {nanpa_regions}") # ['US', 'CA', 'AG', 'AI', ...]

107

108

# Region for specific number

109

number = phonenumbers.parse("+442083661177")

110

region = phonenumbers.region_code_for_number(number)

111

print(f"Number region: {region}") # GB

112

```

113

114

### Supported Regions and Codes

115

116

Access comprehensive lists of supported regions and country codes.

117

118

```python { .api }

119

def supported_regions() -> set:

120

"""

121

Get all supported region codes.

122

123

Returns:

124

Set of two-letter region codes supported by the library

125

"""

126

127

def supported_calling_codes() -> set:

128

"""

129

Get all supported country calling codes.

130

131

Returns:

132

Set of integer country calling codes supported by the library

133

"""

134

```

135

136

**Usage Examples:**

137

138

```python

139

import phonenumbers

140

141

# Get all supported regions

142

regions = phonenumbers.supported_regions()

143

print(f"Number of supported regions: {len(regions)}")

144

print(f"Sample regions: {sorted(list(regions))[:10]}")

145

146

# Get all supported country codes

147

calling_codes = phonenumbers.supported_calling_codes()

148

print(f"Number of calling codes: {len(calling_codes)}")

149

print(f"Sample codes: {sorted(list(calling_codes))[:10]}")

150

```

151

152

### Number Type Support by Region

153

154

Determine which types of phone numbers are supported in specific regions.

155

156

```python { .api }

157

def supported_types_for_region(region_code: str) -> set:

158

"""

159

Get phone number types supported by a region.

160

161

Parameters:

162

- region_code: Two-letter region code to check

163

164

Returns:

165

Set of PhoneNumberType values supported in the region

166

"""

167

168

def supported_types_for_non_geo_entity(country_calling_code: int) -> set:

169

"""

170

Get supported number types for non-geographical entities.

171

172

Parameters:

173

- country_calling_code: Country code for non-geographical entity

174

175

Returns:

176

Set of PhoneNumberType values supported

177

"""

178

```

179

180

**Usage Examples:**

181

182

```python

183

import phonenumbers

184

from phonenumbers import PhoneNumberType

185

186

# Check supported types for a region

187

us_types = phonenumbers.supported_types_for_region("US")

188

print(f"US supports {len(us_types)} number types")

189

190

if PhoneNumberType.MOBILE in us_types:

191

print("US supports mobile numbers")

192

193

if PhoneNumberType.TOLL_FREE in us_types:

194

print("US supports toll-free numbers")

195

196

# Non-geographical entities (like satellite services)

197

satellite_types = phonenumbers.supported_types_for_non_geo_entity(881)

198

print(f"Satellite service types: {satellite_types}")

199

```

200

201

### Example Numbers

202

203

Generate example phone numbers for regions and number types, useful for testing and documentation.

204

205

```python { .api }

206

def example_number(region_code: str) -> PhoneNumber:

207

"""

208

Get an example phone number for a region.

209

210

Parameters:

211

- region_code: Two-letter region code

212

213

Returns:

214

PhoneNumber object with example number, or None if not available

215

"""

216

217

def example_number_for_type(region_code: str, phone_type: PhoneNumberType) -> PhoneNumber:

218

"""

219

Get an example phone number for a specific region and type.

220

221

Parameters:

222

- region_code: Two-letter region code

223

- phone_type: Type of number desired

224

225

Returns:

226

PhoneNumber object with example number, or None if not available

227

"""

228

229

def example_number_for_non_geo_entity(country_calling_code: int) -> PhoneNumber:

230

"""

231

Get example number for non-geographical entity.

232

233

Parameters:

234

- country_calling_code: Country code for non-geographical service

235

236

Returns:

237

PhoneNumber object with example number, or None if not available

238

"""

239

240

def invalid_example_number(region_code: str) -> PhoneNumber:

241

"""

242

Get an example of an invalid number for a region.

243

244

Useful for testing validation logic.

245

246

Parameters:

247

- region_code: Two-letter region code

248

249

Returns:

250

PhoneNumber object that is invalid for the region

251

"""

252

```

253

254

**Usage Examples:**

255

256

```python

257

import phonenumbers

258

from phonenumbers import PhoneNumberType, PhoneNumberFormat

259

260

# Get general example for region

261

us_example = phonenumbers.example_number("US")

262

if us_example:

263

formatted = phonenumbers.format_number(us_example, PhoneNumberFormat.INTERNATIONAL)

264

print(f"US example: {formatted}")

265

266

# Get specific type examples

267

uk_mobile = phonenumbers.example_number_for_type("GB", PhoneNumberType.MOBILE)

268

if uk_mobile:

269

formatted = phonenumbers.format_number(uk_mobile, PhoneNumberFormat.INTERNATIONAL)

270

print(f"UK mobile example: {formatted}")

271

272

uk_toll_free = phonenumbers.example_number_for_type("GB", PhoneNumberType.TOLL_FREE)

273

if uk_toll_free:

274

formatted = phonenumbers.format_number(uk_toll_free, PhoneNumberFormat.INTERNATIONAL)

275

print(f"UK toll-free example: {formatted}")

276

277

# Invalid example for testing

278

invalid = phonenumbers.invalid_example_number("US")

279

if invalid:

280

print(f"Invalid US number: {invalid}")

281

print(f"Is valid: {phonenumbers.is_valid_number(invalid)}")

282

```

283

284

### National Dialing Prefixes

285

286

Access information about national dialing prefixes used within countries.

287

288

```python { .api }

289

def ndd_prefix_for_region(region_code: str) -> str:

290

"""

291

Get the national direct dialing (trunk) prefix for a region.

292

293

This is the prefix (like '0' in UK, '1' in Russia) that must be

294

dialed before area codes when calling within the country.

295

296

Parameters:

297

- region_code: Two-letter region code

298

299

Returns:

300

National dialing prefix string, or None if not applicable

301

"""

302

```

303

304

### Non-Geographical Regions

305

306

Work with special country codes that don't correspond to geographic regions.

307

308

```python { .api }

309

COUNTRY_CODES_FOR_NON_GEO_REGIONS: set

310

"""

311

Set of country calling codes for non-geographical entities.

312

313

These are codes like 800 (International Freephone),

314

881-888 (Global Mobile Satellite System), etc.

315

"""

316

```

317

318

## Constants

319

320

### Core Region Constants

321

322

Essential constants for working with region codes and country calling codes.

323

324

```python { .api }

325

COUNTRY_CODE_TO_REGION_CODE: dict

326

"""

327

Map from country calling codes to region codes.

328

329

Key: Country calling code (int)

330

Value: Tuple of region codes (str) that use this calling code

331

"""

332

333

SUPPORTED_REGIONS: set

334

"""

335

Set of all supported two-letter region codes (ISO 3166-1 alpha-2).

336

337

Includes all regions with defined phone number metadata.

338

"""

339

340

UNKNOWN_REGION: str

341

"""

342

Region code used for unknown or unspecified regions ("ZZ").

343

"""

344

345

COUNTRY_CODES_FOR_NON_GEO_REGIONS: set

346

"""

347

Set of country calling codes for non-geographical entities.

348

349

These are codes like 800 (International Freephone),

350

881-888 (Global Mobile Satellite System), etc.

351

"""

352

353

NON_DIGITS_PATTERN: Pattern

354

"""

355

Compiled regular expression pattern matching non-digit characters.

356

357

Used for normalizing phone number strings.

358

"""

359

```

360

361

### Short Number Constants

362

363

```python { .api }

364

SUPPORTED_SHORT_REGIONS: list

365

"""

366

List of region codes that support short number processing.

367

368

Short numbers include emergency numbers, service codes, etc.

369

"""

370

371

REGION_CODE_FOR_NON_GEO_ENTITY: str

372

"""

373

Special region code for non-geographical entities ("001").

374

"""

375

```

376

377

## Usage Patterns

378

379

### Region Information Lookup

380

381

```python

382

import phonenumbers

383

from phonenumbers import PhoneNumberType

384

385

def get_region_info(region_code):

386

"""Get comprehensive information about a region's numbering plan."""

387

if region_code not in phonenumbers.supported_regions():

388

return {"error": f"Region {region_code} not supported"}

389

390

country_code = phonenumbers.country_code_for_region(region_code)

391

supported_types = phonenumbers.supported_types_for_region(region_code)

392

ndd_prefix = phonenumbers.ndd_prefix_for_region(region_code)

393

394

# Get example numbers for each supported type

395

examples = {}

396

for phone_type in supported_types:

397

example = phonenumbers.example_number_for_type(region_code, phone_type)

398

if example:

399

examples[phone_type] = phonenumbers.format_number(

400

example, phonenumbers.PhoneNumberFormat.INTERNATIONAL

401

)

402

403

return {

404

'region_code': region_code,

405

'country_code': country_code,

406

'ndd_prefix': ndd_prefix,

407

'supported_types': list(supported_types),

408

'examples': examples,

409

'is_nanpa': phonenumbers.is_nanpa_country(region_code)

410

}

411

412

# Example usage

413

us_info = get_region_info("US")

414

print(f"US country code: +{us_info['country_code']}")

415

print(f"US trunk prefix: {us_info['ndd_prefix']}")

416

print(f"Supported types: {len(us_info['supported_types'])}")

417

for phone_type, example in us_info['examples'].items():

418

print(f" {phone_type}: {example}")

419

```

420

421

### Multi-Region Analysis

422

423

```python

424

import phonenumbers

425

426

def analyze_shared_country_codes():

427

"""Find country codes shared by multiple regions."""

428

shared_codes = {}

429

430

for code in phonenumbers.supported_calling_codes():

431

regions = phonenumbers.region_codes_for_country_code(code)

432

if len(regions) > 1:

433

shared_codes[code] = regions

434

435

return shared_codes

436

437

def find_regions_by_criteria(has_mobile=True, has_toll_free=False):

438

"""Find regions that meet specific numbering criteria."""

439

matching_regions = []

440

441

for region in phonenumbers.supported_regions():

442

supported_types = phonenumbers.supported_types_for_region(region)

443

444

meets_criteria = True

445

446

if has_mobile and PhoneNumberType.MOBILE not in supported_types:

447

meets_criteria = False

448

449

if has_toll_free and PhoneNumberType.TOLL_FREE not in supported_types:

450

meets_criteria = False

451

452

if meets_criteria:

453

matching_regions.append(region)

454

455

return matching_regions

456

457

# Example usage

458

shared = analyze_shared_country_codes()

459

print(f"Country codes shared by multiple regions: {len(shared)}")

460

for code, regions in list(shared.items())[:5]:

461

print(f" +{code}: {regions}")

462

463

mobile_regions = find_regions_by_criteria(has_mobile=True)

464

print(f"Regions with mobile support: {len(mobile_regions)}")

465

```

466

467

### Testing Data Generation

468

469

```python

470

import phonenumbers

471

from phonenumbers import PhoneNumberType, PhoneNumberFormat

472

473

def generate_test_numbers(region_code, count_per_type=2):

474

"""Generate test phone numbers for a region."""

475

test_data = {

476

'region': region_code,

477

'country_code': phonenumbers.country_code_for_region(region_code),

478

'valid_numbers': {},

479

'invalid_numbers': []

480

}

481

482

# Get supported types

483

supported_types = phonenumbers.supported_types_for_region(region_code)

484

485

# Generate valid examples for each type

486

for phone_type in supported_types:

487

examples = []

488

for i in range(count_per_type):

489

example = phonenumbers.example_number_for_type(region_code, phone_type)

490

if example:

491

examples.append({

492

'e164': phonenumbers.format_number(example, PhoneNumberFormat.E164),

493

'international': phonenumbers.format_number(example, PhoneNumberFormat.INTERNATIONAL),

494

'national': phonenumbers.format_number(example, PhoneNumberFormat.NATIONAL)

495

})

496

497

if examples:

498

test_data['valid_numbers'][phone_type] = examples

499

500

# Generate invalid examples

501

invalid_example = phonenumbers.invalid_example_number(region_code)

502

if invalid_example:

503

test_data['invalid_numbers'].append({

504

'number': invalid_example,

505

'formatted': phonenumbers.format_number(invalid_example, PhoneNumberFormat.INTERNATIONAL),

506

'is_valid': phonenumbers.is_valid_number(invalid_example)

507

})

508

509

return test_data

510

511

# Example usage

512

test_data = generate_test_numbers("GB", count_per_type=1)

513

print(f"Test data for {test_data['region']} (+{test_data['country_code']}):")

514

for phone_type, examples in test_data['valid_numbers'].items():

515

print(f" {phone_type}: {examples[0]['international']}")

516

```