Skip to main content

API Overview

The tif1 API is a modern Python library for Formula 1 data analysis, telemetry processing, and motorsport analytics. Performance is the primary focus of the design. tif1 is a drop-in replacement for fastf1 in most common use cases. Load times are faster than fastf1 (author-measured; see the Introduction benchmarks). The speed comes from async operations, multi-layer caching, parallel HTTP fetching, and an opt-in Polars backend. tif1 serves data scientists, motorsport engineers, application developers, and racing enthusiasts. These users can work efficiently with Formula 1 data at scale.

What Makes tif1 Different

tif1 stands apart from other F1 data libraries through several key innovations:
  • Performance: Every component, from HTTP fetching to DataFrame construction, is optimized for speed. Async operations run in parallel. Caching happens at multiple layers (memory + SQLite). The opt-in Polars backend gives memory-efficient processing for large datasets.
  • Production Architecture: tif1 is built for production use, not only for research. It includes circuit breakers, retry logic, connection pooling, and DNS-over-HTTPS support. Errors carry structured context. Loading falls back to the next CDN source when one source fails.
  • Developer Experience: Type hints throughout the codebase enable IDE autocomplete and type checking. Clear error messages with structured context make debugging quick. Consistent naming conventions make the API predictable and easy to learn.
  • Flexible Data Access: Load only the data that the task needs. Skip telemetry for faster lap time analysis. Load everything for full session exploration. The API adapts to each use case.
  • Modern Python Practices: tif1 supports Python 3.11 through 3.15. It uses modern type hints and async/await patterns. The codebase follows strict linting rules (Ruff) and maintains high test coverage.

Design Philosophy

The tif1 API is built on a foundation of carefully considered design principles that guide every architectural decision and implementation detail:

Performance First

Performance is not just a feature—it is the core reason tif1 exists. Every component has been profiled, optimized, and benchmarked:
  • Async Operations: Network I/O uses niquests, a modern fork of requests, with async/await for parallel fetches. This enables parallel fetching of multiple data sources at the same time. tif1 can fetch all data for a 20-driver race session in parallel.
  • Multi-Layer Caching: An in-memory LRU cache holds hot data. A SQLite-backed persistent cache holds all fetched data. Cache hits return data in milliseconds rather than seconds. Cache keys are the payload paths, and cached payloads do not expire.
  • Parallel Fetching: When loading session data, tif1 fetches the per-driver lap files, weather, and race control messages in one parallel batch. Telemetry payloads are also fetched in parallel. The fetches use asyncio.gather.
  • Opt-in Polars Backend: Polars is installed with tif1. The Polars backend serves large datasets, for example multiple seasons and comparative analysis. Polars is a columnar library built for fast, memory-efficient DataFrame operations. The backend is lazy-loaded and can be switched at runtime.
  • Optimized JSON Parsing: tif1 uses orjson (written in Rust) instead of Python’s stdlib json. orjson parses JSON faster than the stdlib. The speed matters when processing megabytes of telemetry data.
  • Connection Pooling: HTTP sessions use connection pooling to reuse TCP connections across requests. This avoids a new TCP and TLS handshake for each request.

Simplicity and Ergonomics

Complex operations should stay simple. The API hides complexity behind consistent interfaces:
  • Minimal Entry Points: Most users only need get_session() to start working with F1 data. Everything else is discoverable through the returned Session object via IDE autocomplete.
  • Sensible Defaults: All optional parameters have sensible defaults. session.load() fetches laps, weather, messages, and all telemetry by default. Disable unneeded data sources for faster loading.
  • Fuzzy Matching: Event names support aliases and fuzzy matching—“spa”, “belgium”, “Belgian Grand Prix”, and “Spa-Francorchamps” all work. Session types accept both full names (“Qualifying”) and short codes (“Q”). This reduces friction and makes the API more forgiving.
  • Progressive Disclosure: Basic usage is simple, but advanced features are available when needed. Start with session.laps for quick analysis, then dive into driver.get_lap(n).get_telemetry() for detailed telemetry work.
  • Method Chaining: Where appropriate, methods return objects that support further operations, enabling natural workflows like session.get_driver("VER").get_fastest_lap().get_telemetry().

Predictability and Consistency

The API should be easy to learn and remember:
  • Consistent Naming: Methods follow clear patterns—get_* for retrieval operations, load() for data loading, clear() and invalidate() for cache operations. Attributes use snake_case, classes use PascalCase.
  • Clear Data Hierarchies: The object model mirrors F1’s structure: Session contains Driver objects, which contain Lap objects, which contain Telemetry data. This mental model matches how most users think about F1 data.
  • Type Hints: Most public functions and methods include type hints. An IDE can show the expected parameters and the return values. This reduces the need to consult documentation.
  • Structured Errors: Exceptions include structured context (not just error messages) for programmatic error handling. A DataNotFoundError includes the year, event, and session that were not found.

Compatibility

Existing fastf1 users should be able to migrate with minimal friction:
  • Drop-in Replacement: The core API (get_session(), Session.laps, Driver objects) matches fastf1’s interface. Most fastf1 code works with tif1 by just changing the import.
  • Compatibility Layer: The tif1.fastf1_compat module provides shims for fastf1-specific functions like set_log_level() and Cache.enable_cache().
  • DataFrame Compatibility: DataFrames returned by tif1 use the fastf1 column names. Most existing analysis code needs no changes.
  • Migration Path: Both libraries can run side-by-side during migration. Validate the behavior of each piece of code, then move it to tif1.

Extensibility and Customization

Advanced users should be able to customize behavior:
  • Configuration System: Global configuration via get_config() tunes performance parameters (max workers, timeouts, validation). The same call switches backends (pandas/polars). It also controls behavior (ultra cold start mode, DNS-over-HTTPS).
  • Modular Architecture: The library is split into focused modules (http_session, async_fetch, cache, cdn). Each module has one job and can be imported on its own.
  • Backend Abstraction: pandas and polars sessions share the same entry points. The lib setting selects the backend.
  • Cache Management: get_cache() exposes the cache location and tiers. Clear everything, invalidate one tier (memory, JSON, or telemetry), or disable caching per session for testing.
  • Retry and Circuit Breaker: Configurable retry logic uses exponential backoff. Circuit breaker patterns handle transient network failures gracefully.

Quick Start

Get started with tif1 in seconds. The library handles all the complexity of data fetching, parsing, caching, and DataFrame construction behind a simple, consistent interface:

What Happens Behind the Scenes

get_session() resolves the names and returns a Session handle without a fetch. The first data access, or session.load(), runs the remaining steps:
  1. Input Validation and Normalization
    • Validates that the year is 2018 or later
    • Resolves the event name: exact name first, then the circuit, city, and country alias table, then fuzzy matching
    • Normalizes the session name (accepts “Race”, “R”, “race”, “RACE”, etc.)
    • Raises ValueError if validation fails
  2. Schedule Lookup
    • Reads the season schedule. Past seasons use the vendored files in src/tif1/data/schedules/f1schedule/
    • The current and future seasons use the live f1schedule file, cached for schedule_ttl_hours (default 6), with the vendored file as fallback
    • Retrieves event metadata: official name, location, date, session times
    • Determines available sessions for the event (standard vs sprint weekend format)
    • Validates the requested session exists for this event
  3. Cache Check (SQLite)
    • Builds the cache key from the payload path (year, event, session, file name)
    • Queries the SQLite cache database in tif1’s OS-dependent cache directory by default
    • Cached payloads do not expire; only “missing payload” verdicts (missing_payloads_ttl_days) and the live season schedule row (schedule_ttl_hours) expire
    • On a cache hit, parses the stored payload or loads a stored DataFrame without network I/O
    • On a cache miss, proceeds to fetch from the CDN
  4. CDN URL Construction
    • Builds URLs for all requested data sources (laps, telemetry, weather, messages)
    • Uses a three-source CDN chain (jsDelivr primary, Hugging Face buckets fallback, StaticDelivr backup) pointing to TracingInsights GitHub data repositories
    • Constructs fallback URLs in case primary CDN fails
  5. Parallel Async Fetching
    • Creates async tasks for each data source and runs them with asyncio.gather
    • Fetches all data sources in parallel (not sequential) using niquests
    • Uses connection pooling to reuse TCP connections
    • Implements retry logic with exponential backoff for transient failures
    • Falls back to alternative CDN sources if primary fails
  6. JSON Parsing
    • Parses JSON responses using orjson (Rust-based)
    • Checks that each payload is a JSON object
    • Raises InvalidDataError if data is corrupted or malformed
    • Extracts nested data structures (lap arrays, telemetry points, etc.)
  7. DataFrame Construction
    • Converts parsed JSON into pandas or Polars DataFrames based on config
    • Applies column renaming to match fastf1 conventions
    • Sets data types: on pandas, times are timedelta64[ns] and LapNumber is float64; on Polars, times are Duration("ns")
    • Uses the category dtype on pandas for Driver, Team, Compound, and TrackStatus
    • Reorders columns to standard layout
    • Adds computed columns (LapTimeSeconds, per-lap weather columns, etc.)
    • Fills missing values with NaN or NaT
  8. Payload Validation (Optional)
    • Runs on each payload fetched from the CDN, before DataFrame construction and caching
    • validate_data covers weather and race control messages, validate_lap_times the lap files, and validate_telemetry the telemetry files
    • Checks structure, field aliases, and array lengths with pydantic-free fast paths
    • Off by default (all three keys are False), and ultra-cold loads skip it
  9. Cache Storage
    • Stores raw JSON payloads in SQLite, compressed with zstd (zlib without a zstd binding)
    • Stores built DataFrames as pickled blobs, compressed with lz4 (zstd without lz4)
    • Writes telemetry payloads to a separate telemetry table
  10. Object Construction
    • get_session() returns the Session handle before any fetch
    • Data properties (laps, weather, race_control_messages, …) fetch their data on first access
    • get_driver() and get_lap() build Driver and Lap objects on request
    • Telemetry loads per lap on first access (Session → Driver → Lap → Telemetry)
Cached data loads without network I/O. A cold load spends most of its time on the network.

Performance Characteristics

Use this performance profile to optimize workflows:
  • Cache Hit (Warm): No network I/O
    • Data loaded from SQLite cache
    • DataFrame deserialization from binary format
    • No network I/O
  • Cache Miss (Cold): Network-bound
    • Parallel async fetching of all data sources
    • JSON parsing and DataFrame construction
    • Cache storage for future use
    • Dominated by network latency, not CPU
  • Partial Cache Hit: Only the missing payloads cost network time
    • Some data sources cached, others fetched
    • Only missing data sources are fetched
    • Faster than full cold start
  • Ultra Cold Start Mode: On by default (ultra_cold_start=True)
    • Applies to sessions that are not in the cache yet
    • Skips cache reads, payload validation, and retry delays
    • Still writes the fetched payloads to the cache for the next load
    • Disable with config.set("ultra_cold_start", False)
  • Polars Backend: Columnar DataFrames
    • Time columns are Duration instead of timedelta64; the frames are PolarsLaps and PolarsTelemetry
    • Enable with config.set("lib", "polars"), or lib="polars" for one session

Entry Points

The tif1 API exposes five primary entry points that serve as the foundation for all data access, configuration, and cache management. For most use cases, these functions are the only imports needed:

Detailed Entry Point Usage

get_session(year, gp, session, enable_cache=None, lib=None)

The primary entry point for loading Formula 1 session data. The function accepts multiple input formats. It returns a Session handle; session.load(...) selects which data gets fetched. Function Signature:
Basic Usage Examples:
Selective Data Loading: Control exactly what data gets loaded to optimize performance for each specific use case:
Advanced Usage:
Parameters Deep Dive:
  • year (int): Championship year, 2018 or later
    • 2018 onwards: Historical data as published by TracingInsights
    • 1950 onwards: Ergast results, lap times, pit stops and standings (the TracingInsights Stats repository, Jolpica as fallback)
    • Current season: Partial data (as events occur)
    • Earlier years: Not supported (ValueError)
  • gp (str | int): Event name with flexible matching, or the round number
    • Official names: “Monaco Grand Prix”, “British Grand Prix”
    • Circuit names: “Silverstone”, “Spa-Francorchamps”, “Monza”
    • Location names: “Monaco”, “Belgium”
    • Partial matches: “monaco”, “belgian”
    • Case insensitive: “MONACO”, “Monaco”, “monaco” all work
    • Round numbers: 12 resolves through the schedule for that year
    • Circuit, city, and country aliases resolve per season (“Spa”, “Interlagos”, “USA”)
    • An alias for an event that is not on that season’s calendar raises ValueError (“Suzuka” in 2021)
  • session (str | int): Session name with multiple formats, or a 1-based index
    • Full names: “Practice 1”, “Practice 2”, “Practice 3”, “Qualifying”, “Sprint”, “Race”
    • Short codes: “FP1”, “FP2”, “FP3”, “Q”, “S”, “R”
    • Sprint weekends: “Sprint Qualifying” or “SQ”, “Sprint Shootout” or “SS”
    • Case insensitive: “race”, “RACE”, “Race” all work
    • Normalized internally to the canonical form
  • enable_cache (bool | None): SQLite cache for this session
    • None: Use the global config setting (default)
    • True: Read and write the cache
    • False: Fetch from the CDN; nothing is written to the cache
    • Useful for: debugging, getting the latest data, cache corruption
  • lib (Literal[“pandas”, “polars”] | None): DataFrame backend
    • None: Use the global config setting (default)
    • "pandas": Use pandas DataFrames (more compatible, more features)
    • "polars": Use Polars DataFrames (faster, more memory efficient)
    • Can be changed per session without affecting the global config
The data selection flags belong to session.load(laps, telemetry, weather, messages):
  • laps (bool): Fetch lap timing data
    • Includes: lap times, sector times, tire compounds, tire life, positions, pit stops
    • Forced to True when telemetry=True
    • Required for: almost all analysis workflows
  • telemetry (bool): Fetch telemetry for every lap of every driver
    • Includes: speed, RPM, throttle, brake, gear, DRS, position (X/Y/Z)
    • Sampling rate: roughly 7-9 samples per second
    • Slowest option: one payload per driver lap
    • Leave False and call driver.get_lap(n).telemetry to fetch single laps on demand
  • weather (bool): Fetch weather conditions
    • Includes: air temp, track temp, humidity, pressure, wind speed/direction, rainfall
    • Sampling rate: ~1 sample per minute
    • Required for: understanding tire performance, strategy decisions
  • messages (bool): Fetch race control messages
    • Includes: flags (yellow, red, green), safety cars, penalties, DRS status
    • Required for: understanding race incidents, strategy impacts
Return Value: Returns a Session object with the following key attributes and methods:
Exception Handling:
Performance Tips:
  1. Load only the needed data: Disable unused data sources
  2. Use the cache: Keep enable_cache at its default unless necessary
  3. Consider Polars for large datasets: Polars is built for memory-efficient work
  4. Batch load sessions: Run blocking loads in threads for parallel loading

get_events(year)

Retrieve the complete event schedule for a championship year. The schedule includes all Grand Prix events with metadata, dates, locations, and session structures. Function Signature:
Basic Usage:
Filtering and Analysis:
Session Structure Analysis:
DataFrame Columns Explained:
  • RoundNumber (int): Round number in the championship (0 for pre-season testing)
  • EventName (str): Short event name (for example, “Monaco Grand Prix”)
  • OfficialEventName (str): Full official name (for example, “FORMULA 1 GRAND PRIX DE MONACO 2024”)
  • Location (str): Circuit location or city (for example, “Monaco”, “Silverstone”)
  • Country (str): Country name (for example, “Monaco”, “United Kingdom”)
  • EventDate (datetime64): Date of the main race
  • EventFormat (str): “conventional”, “sprint_qualifying” (sprint weekends), or “testing”
  • Session1-5 (str): Session names (“Practice 1”, “Qualifying”, “Race”, etc.)
  • Session1-5Date (datetime): Local date and time for each session, with the UTC offset
  • Session1-5DateUtc (datetime64): Session start in UTC, without a timezone (for example, 13:00 for a 15:00+02:00 local start)
  • F1ApiSupport (bool): Whether F1 official API supports this event
  • GmtOffset (str): UTC offset of the circuit
Use Cases:
Performance Notes:
  • Schedule files for 2018-2026 ship with the package. Past seasons load from them without network I/O
  • The current and future seasons use the live f1schedule file, cached for schedule_ttl_hours (default 6). The vendored file is the fallback
See Events API for complete documentation.

get_sessions(year, event)

List all available sessions for a specific event, accounting for standard vs sprint weekend formats. Function Signature:
Usage Examples:
Use Cases:
  • Validate session existence before loading
  • Build UI dropdowns for session selection
  • Iterate through all sessions in an event
  • Handle standard vs sprint weekend differences
See Events API for complete documentation.

get_config()

Access global configuration singleton:
See Config API for all available settings.

get_cache()

Manage the SQLite-backed cache:
See Cache API for complete cache management.

Core Objects

The tif1 API is built around a clear object hierarchy that mirrors the structure of Formula 1 data. Understanding this hierarchy is key to effective use of the library.

Primary Objects

These are the main objects that tif1 users interact with:

Session

The Session object represents an entire Formula 1 session (Practice, Qualifying, Sprint, or Race). It is the primary container for all session data. Key Attributes:
  • session.laps - All lap timing data from all drivers as a DataFrame
  • session.weather - Weather conditions throughout the session
  • session.race_control_messages - Official race control messages and flags
  • session.results - Classification table, one row per driver in finishing order
  • session.drivers - List of driver numbers in finishing order (for example, [‘33’, ‘63’, ‘44’])
  • session.drivers_df - DataFrame with driver codes, teams, and numbers
  • session.session_info - Session metadata in the fastf1 layout (Meeting, Type, Name, StartDate, EndDate, GmtOffset)
  • session.track_status, session.session_status - Track and session status changes, derived from the race control messages
  • session.car_data, session.pos_data - Lazy dict of each driver’s telemetry for the whole session, keyed by driver number
  • session.event_name, session.session_name - Plain event and session names (session.gp and session.session are URL-encoded)
  • session.event - Schedule row for the event (location, country, dates)
  • session.date - Session start as a pd.Timestamp
Key Methods:
  • get_driver(code) - Get a Driver object for a specific driver
  • get_fastest_laps(by_driver=True) - Fastest lap per driver, or the overall fastest lap
  • get_circuit_info() - Corner positions, marshal lights and sectors, and the track rotation
  • laps.pick_driver(code) - All laps for a specific driver
  • load() - Explicitly load data (usually called automatically)
Example:
See Session API for complete documentation.

Driver

The Driver object represents a specific driver within a session and provides convenient access to driver-specific data and operations. Key Attributes (a Driver is a pandas Series; read fields with driver[...]):
  • driver['Abbreviation'] - Three-letter driver code (for example, ‘VER’)
  • driver['FullName'] - Full driver name (for example, ‘Max Verstappen’)
  • driver['TeamName'] - Team name (for example, ‘Red Bull Racing’)
  • driver['DriverNumber'] - Racing number as a string (for example, ‘1’)
  • driver.laps - All laps completed by this driver as a Laps DataFrame
Key Methods:
  • get_lap(lap_number) - Get a specific lap by number
  • get_fastest_lap() - Get the driver’s fastest lap (one-row Laps frame)
  • get_fastest_lap_tel() - Get telemetry for the fastest lap
  • get_lap(lap_number).telemetry - Get telemetry for a specific lap
Example:
See Driver API for complete documentation.

Lap

The Lap object represents a single lap by a driver and provides access to high-frequency telemetry data for that specific lap. Key Attributes (a Lap is a pandas Series; read columns with lap[...]):
  • lap.lap_number - Lap number in the session
  • lap.driver - Three-letter driver code
  • lap['LapTime'] - Total lap time as a timedelta; lap['LapTimeSeconds'] as float seconds
  • lap['Sector1Time'], lap['Sector2Time'], lap['Sector3Time'] - Sector times (timedeltas)
  • lap['Compound'] - Tire compound used
  • lap.telemetry - Telemetry DataFrame for this lap (fetched on first access)
Key Methods:
  • get_telemetry() - Load telemetry data for this lap
  • get_car_data(), get_pos_data() - fastf1-compatible aliases; both return the full telemetry frame. pad adds samples of the neighbouring laps
The lap row also carries a weather sample that the source data matched to the lap (lap['AirTemp'], lap['TrackTemp'], lap['Rainfall'], …). That match is misaligned for many laps. lap.get_weather_data() picks the sample from session.weather_data with the fastf1 rule. Example:
See Lap API for complete documentation.

Data Models

These objects represent structured data returned by the API:

Laps

A DataFrame containing lap timing data with rich filtering and analysis methods. Columns:
  • Driver - Driver code
  • LapNumber - Sequential lap number
  • LapTime - Total lap time (timedelta64[ns] on pandas, Duration on polars)
  • LapTimeSeconds - Total lap time as float seconds on both backends
  • Sector1Time, Sector2Time, Sector3Time - Sector times (same dtype as LapTime)
  • Compound - Tire compound (SOFT, MEDIUM, HARD, INTERMEDIATE, WET)
  • TyreLife - Age of tires in laps
  • IsPersonalBest - Boolean flag for personal best lap
  • Position - Track position at lap completion
  • PitInTime, PitOutTime - Pit stop timing
  • TrackStatus - Track condition flags
Methods:
  • pick_driver(code) - Filter to specific driver
  • pick_fastest() - Get fastest lap
  • pick_compounds(compounds) - Filter by tire compound
  • pick_track_status(status, how="equals") - Filter by the lap’s track status codes (how is equals, contains, excludes, any, or none)
See Laps Model for complete documentation.

Telemetry

A DataFrame of telemetry samples, at about 7-9 Hz. Time is relative to the lap start. Columns:
  • Date, SessionTime - Wall-clock date and session time of the sample
  • Distance - Distance along track (meters)
  • Speed - Speed (km/h)
  • RPM - Engine RPM
  • Throttle - Throttle position (0-100%)
  • Brake - Brake applied (boolean on both backends)
  • DRS - DRS status (0=closed, 1=open)
  • nGear - Current gear (1-8)
  • X, Y, Z - 3D position coordinates
Usage:
See Telemetry Model for complete documentation.

SessionResults

The session classification from session.results, one row per driver in finishing order. On pandas it is a SessionResults indexed by driver number. On polars it is a PolarsSessionResults, with DriverNumber as a column. Columns:
  • DriverNumber, Abbreviation - Racing number (string) and three-letter code
  • FirstName, LastName, FullName - Driver names
  • TeamName, TeamColor - Team name and hex color without # (for example, “3671C6”)
  • HeadshotUrl - Driver photo URL
  • Position (float, 1 to N) and ClassifiedPosition (string, “1” to “N”) - Finishing position
  • Status - The official status (for example “Finished”, “Retired”) for races and sprints; “Finished” for practice and qualifying
  • Laps - Laps completed (float)
  • GridPosition, Points - From the official Ergast classification of races and sprints. NaN in every other session
  • Q1 to Q3, Time - From the official Ergast classification (Race, Sprint, and Qualifying). Practice is classified from the laps, as in fastf1: Time is the best lap that is not deleted. Sprint Qualifying and Sprint Shootout fill Q1 to Q3 from the best accurate lap of each segment
Where the upstream driver list is only sorted by car number, tif1 rebuilds the order from the laps. The rebuilt order of a race or sprint uses laps completed, then the position on the last lap. Practice uses the best lap. Sprint Qualifying and Sprint Shootout always rank by Q3, then Q2, then Q1. A post-race penalty does not show in lap data, so this order can differ from the official result.
See SessionResults Model for complete documentation.

CircuitInfo

Track markers and orientation, from session.get_circuit_info(). Attributes:
  • corners - DataFrame of corner markers (X, Y, Number, Letter, Angle, Distance)
  • marshal_lights, marshal_sectors - DataFrames with the same columns (from corners.json, or from the MultiViewer API for older seasons)
  • rotation - Track map rotation in degrees (float)
  • add_marker_distance(reference_lap) - Fill the Distance column of the markers from a lap’s telemetry
See CircuitInfo Model for complete documentation.

API Categories

Core data access

Essential APIs for loading and working with F1 data:
  • Core API - Session, Driver, Lap classes and data loading
  • Models - Data model classes and structures
  • Events - Event and session discovery
  • Schedule - Schedule validation and schema

Data Pipeline

Internal data transformation and fetching:
  • Async Fetch - Parallel HTTP fetching with niquests
  • HTTP - HTTP session and networking
  • HTTP Session - Connection pooling and DoH support
  • CDN - Multi-source CDN management with fallback

Configuration & Cache

Performance and reliability management:
  • Config - Global configuration management
  • Cache - SQLite-backed caching system
  • Retry - Circuit breaker and retry logic

Visualization & Tools

User-facing utilities:
  • Plotting - F1-themed visualization utilities
  • CLI - Command-line interface
  • Jupyter - Notebook integration and rich displays

Utilities & Helpers

Supporting functionality:
  • Utils - General utility functions
  • Utilities - Helper functions for configuration and logging
  • Core Utils - Internal utilities for DataFrame operations
  • Types - Type definitions and hints
  • Validation - Pydantic models and data validation
  • Fuzzy - Fuzzy string matching for event/session names

Compatibility & Errors

Integration and error handling:

Common Workflows

Load and explore session

Analyze driver performance

Parallel data loading

Configuration and Optimization


Error Handling

tif1 uses a hierarchy of specific exceptions. These exceptions help with common issues:

Exception Hierarchy

Common Exceptions

  • DataNotFoundError: No CDN has data for the requested session, driver, or lap
  • NetworkError: All CDN sources failed or timed out
  • InvalidDataError: The data fetched from the CDN was corrupted
  • DriverNotFoundError: The driver code provided is not in this session
  • LapNotFoundError: The requested lap number does not exist for this driver
  • CacheError: Reserved for cache failures. tif1 logs cache failures and does not raise it at present
  • SessionNotLoadedError: Reserved for data access before a load. tif1 loads data lazily and does not raise it at present
A year before 2018 or an unknown session name raises ValueError from get_session(), not DataNotFoundError. An event name that matches no event raises EventNotFoundError, a ValueError subclass. A fuzzy match needs a score of at least 70. An alias for an event that is not on that season’s calendar raises EventNotInSeasonError, a subclass of EventNotFoundError. A typo such as “Monacco” resolves to the closest event, and tif1 logs the correction. Check session.event_name when the input is uncertain.

Error handling example

See Exceptions API for complete documentation.

Performance Tips

  1. Use async methods for parallel loading: Several loads can run at the same time
  2. Keep ultra-cold start on for first loads: It is the default
  3. Use polars lib for large datasets: Select it per session or with config.set("lib", "polars")
  4. Keep validation off in production: validate_data is False by default. Turn it on only to debug a payload
  5. Increase concurrency for bulk operations: Faster parallel fetching
See Best Practices for more optimization tips.

Type Hints

Most public APIs include type hints for IDE support:
See Types API for complete type definitions.

Next Steps

  • Core API - Start with Session, Driver, and Lap classes
  • Tutorials - Learn through practical examples
  • Best Practices - Optimize analysis code
  • FAQ - Common questions and answers

Core API

Session, Driver, Lap

Models

Data models

Events

Event discovery

Examples

Code examples
Last modified on October 30, 2026