Ctrl + k

or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/typeshed-client@2.8.x

docs

index.md
tile.json

tessl/pypi-typeshed-client

tessl install tessl/pypi-typeshed-client@2.8.4

A library for accessing stubs in typeshed.

quick-start.mddocs/guides/

Quick Start Guide

This guide will help you get started with typeshed_client quickly.

Installation

pip install typeshed_client

Basic Workflow

1. Find a Stub File

from typeshed_client import get_stub_file

# Find the path to typing module's stub
stub_path = get_stub_file('typing')

if stub_path:
    print(f"Found stub at: {stub_path}")
else:
    print("Stub not found")

Key Points:

  • Always check for None return value
  • Works with dotted module names like 'collections.abc'
  • Returns absolute path to .pyi stub file

2. Get Names from a Stub

from typeshed_client import get_stub_names

# Get all names defined in the collections module
names = get_stub_names('collections')

if names:
    # Filter to exported (public) names
    exported = [name for name, info in names.items() if info.is_exported]
    print(f"Exported names: {exported[:10]}")
    
    # Check if specific name exists
    if 'OrderedDict' in names:
        print("OrderedDict is defined in collections")
else:
    print("Module not found")

Key Points:

  • Returns NameDict (dict[str, NameInfo]) or None
  • Check info.is_exported to find public API
  • Each NameInfo contains AST node and metadata

3. Resolve Names Across Modules

from typeshed_client import Resolver, ImportedInfo, NameInfo

# Create a resolver (reuse for multiple lookups)
resolver = Resolver()

# Resolve where OrderedDict is actually defined
result = resolver.get_fully_qualified_name('collections.OrderedDict')

if result is None:
    print("Name not found")
elif isinstance(result, ImportedInfo):
    print(f"Imported from: {'.'.join(result.source_module)}")
    print(f"Name: {result.info.name}")
elif isinstance(result, NameInfo):
    print("Defined directly in collections")

Key Points:

  • Resolver maintains internal caches - reuse instances
  • Returns union type - always check with isinstance()
  • Follows import chains to find original definitions

Common Tasks

Check Module Availability

from typeshed_client import get_stub_file

modules = ['typing', 'asyncio', 'dataclasses']

for module in modules:
    if get_stub_file(module):
        print(f"✓ {module} has stub support")
    else:
        print(f"✗ {module} lacks stub support")

Analyze Class Structure

from typeshed_client import get_stub_names
import ast

names = get_stub_names('typing')

if names and 'TypedDict' in names:
    class_info = names['TypedDict']
    
    # Check if it's a class
    if isinstance(class_info.ast, ast.ClassDef):
        print(f"Class: {class_info.name}")
        print(f"Exported: {class_info.is_exported}")
        
        # Get methods
        if class_info.child_nodes:
            methods = list(class_info.child_nodes.keys())
            print(f"Methods: {methods}")

Version-Specific Stubs

from typeshed_client import get_search_context, get_stub_names

# Parse for Python 3.9
ctx_39 = get_search_context(version=(3, 9))
names_39 = get_stub_names('typing', search_context=ctx_39)

# Parse for Python 3.12
ctx_312 = get_search_context(version=(3, 12))
names_312 = get_stub_names('typing', search_context=ctx_312)

# Compare
if names_39 and names_312:
    new_names = set(names_312.keys()) - set(names_39.keys())
    print(f"Names added after 3.9: {new_names}")

Platform-Specific Analysis

from typeshed_client import get_search_context, get_stub_names

# Get Windows-specific definitions
ctx_windows = get_search_context(platform='win32')
names_windows = get_stub_names('os', search_context=ctx_windows)

# Get Linux-specific definitions
ctx_linux = get_search_context(platform='linux')
names_linux = get_stub_names('os', search_context=ctx_linux)

if names_windows and names_linux:
    windows_only = set(names_windows.keys()) - set(names_linux.keys())
    print(f"Windows-only functions: {windows_only}")

Error Handling

Handling Missing Modules

from typeshed_client import get_stub_file, get_stub_names

module_name = 'some_module'

# Check if stub exists
stub_path = get_stub_file(module_name)
if stub_path is None:
    print(f"No stub found for {module_name}")
    # Handle missing stub case
else:
    # Parse the stub
    names = get_stub_names(module_name)
    if names:
        print(f"Successfully parsed {len(names)} names")

Strict Parsing

from typeshed_client import get_search_context, get_stub_names
from typeshed_client.parser import InvalidStub

# Enable strict mode
ctx = get_search_context(raise_on_warnings=True)

try:
    names = get_stub_names('module', search_context=ctx)
    print(f"✓ Valid stub: {len(names)} names")
except InvalidStub as e:
    print(f"✗ Invalid stub: {e}")

Working with AST Nodes

Examine Function Signatures

from typeshed_client import get_stub_names
import ast

names = get_stub_names('typing')

if names:
    for name, info in names.items():
        if isinstance(info.ast, ast.FunctionDef):
            # Get arguments
            args = [arg.arg for arg in info.ast.args.args]
            
            # Get return type
            ret = "Any"
            if info.ast.returns:
                ret = ast.unparse(info.ast.returns)
            
            print(f"{name}({', '.join(args)}) -> {ret}")

Handle Overloaded Functions

from typeshed_client import get_stub_names, OverloadedName
import ast

names = get_stub_names('typing')

if names:
    for name, info in names.items():
        if isinstance(info.ast, OverloadedName):
            print(f"{name} has {len(info.ast.definitions)} overloads")
            
            for i, defn in enumerate(info.ast.definitions, 1):
                if isinstance(defn, ast.FunctionDef):
                    args = [arg.arg for arg in defn.args.args]
                    print(f"  Overload {i}: ({', '.join(args)})")

Trace Imports

from typeshed_client import get_stub_names, ImportedName

names = get_stub_names('collections')

if names:
    for name, info in names.items():
        if isinstance(info.ast, ImportedName):
            source = '.'.join(info.ast.module_name)
            if info.ast.name:
                print(f"{name} <- {source}.{info.ast.name}")
            else:
                print(f"{name} <- {source} (module)")

Configuration

Custom Search Paths

from pathlib import Path
from typeshed_client import get_search_context, get_stub_file

# Search in virtual environment
venv = Path('./venv/lib/python3.11/site-packages')
ctx = get_search_context(search_path=[venv])

# Find third-party package stubs
path = get_stub_file('requests', search_context=ctx)
if path:
    print(f"Found: {path}")

Custom Typeshed

from pathlib import Path
from typeshed_client import get_search_context, get_stub_file

# Use development version of typeshed
dev_typeshed = Path('/path/to/custom/typeshed')
ctx = get_search_context(typeshed=dev_typeshed)

path = get_stub_file('typing', search_context=ctx)
if path and str(dev_typeshed) in str(path):
    print("Using custom typeshed")

Best Practices

  1. Check for None: Always verify return values before using them
  2. Reuse Contexts: Create SearchContext once, reuse for consistency
  3. Cache Resolvers: Keep single Resolver instance for multiple lookups
  4. Type Guards: Use isinstance() for union types
  5. Handle Errors: Wrap operations in try-except when appropriate

Next Steps

  • Explore Real-World Scenarios for comprehensive examples
  • Check Edge Cases for advanced patterns
  • Review API Reference for detailed documentation

Quick Reference

Essential Functions

# Finding stubs
get_stub_file(module_name) -> Optional[Path]
get_stub_ast(module_name) -> Optional[ast.Module]
get_stub_names(module_name) -> Optional[NameDict]

# Resolving names
resolver = Resolver()
resolver.get_fully_qualified_name(name) -> ResolvedName

# Configuration
get_search_context(version=..., platform=...) -> SearchContext

Always Check These

  • ✓ Check for None returns
  • ✓ Use isinstance() for type checking
  • ✓ Verify module.exists before accessing module.names
  • ✓ Check info.is_exported for public APIs
  • ✓ Handle InvalidStub exceptions when using strict mode