Skip to main content

Automate type hint generation in a single line.

Project description

LazyTypeHint

Type hint any Python (nested) data structure! Dictionaries, callables, Pandas DataFrames...

pip install lazy-type-hint

Quick examples

from lazy_type_hint import LazyTypeHint, LazyTypeHintLive

data = [1,2,3]
LazyTypeHint().from_data(data, class_name="MyClass").to_file("file.py")
LazyTypeHint().from_data(data, class_name="MyClass").to_string()
data_type_hinted = LazyTypeHintLive().from_data(data, class_name="MyClass")

Main features

  1. Get corresponding type hints from any given data structure and with mutltiple parsing options. Export it as a file or as a string.

       from lazy_type_hint import LazyTypeHint, ParsingStrategies
    
       # INPUT
       people = [
           {
               "name": "Peter",
               "age": 40,
               "kids": (
                   {
                       "name": "Peter Jr",
                       "age": 10,
                   },
                   {
                       "name": "Peter Jr2",
                       "age": 8,
                   },
               ),
           },
           {
               "name": "Kevin",
               "age": 42,
               "job": "Carpenter",
               "kids": (
                   {
                       "name": "Peter Jr",
                       "age": 10,
                   },
               ),
           },
       ]
    
       people_type_hint = (
           LazyTypeHint(
               strategies=ParsingStrategies(
                   min_height_to_define_type_alias=2,
                   tuple_size_strategy="any size",
               )
           )
           .from_data(people, class_name="People")
           .to_string()
       )
       print(people_type_hint)
    
     # OUTPUT
     from typing import List, Tuple, TypedDict
     from typing_extensions import NotRequired
    
    
     class PeopleDictKidsDict(TypedDict):
         name: str
         age: int
    
    
     class PeopleDict(TypedDict):
         name: str
         age: int
         kids: Tuple[PeopleDictKidsDict, ...]
         job: NotRequired[str]
    
     People = List[PeopleDict]
    
  2. [EXPERIMENTAL] Get type hints live with LazyTypeHintLive. The API changes its local interface as soon as you use it, allowing to automatically infer and reuse your type hints after executing your program once.

    Before executing the code After executing the code
    Before executing the code After executing the code

    This will allow you to:

    Perform static analysis to detect issues After executing the code
    Reuse your available type hints After executing the code
    Have full autocompletion support from your IDE After executing the code
  3. Easily type hint your files (YAML, JSON) and parse extra comments found within this file as part of the type hint docstrings. Given a yaml file like:

     # Collection of sensors
     sensors:
       - name: Sensor1
         # Type of sensor used
         sensor_type: Temperature
         location: Living Room
         # Maximum amount allowed.
         # NOTE: Only 3 are available
         threshold: 25  # Units: [C]
    
       - name: Sensor2
         sensor_type: Humidity
         location: Bedroom
         threshold: 60
    
       - name: Sensor3
         sensor_type: Pressure
         location: Kitchen
         threshold: 1000
    

    And the code:

       from lazy_type_hint import LazyTypeHint
    
    
     def load_yaml_file(file_path):
         with open(file_path, "r") as file:
             data = yaml.safe_load(file)
         return data
    
    
     print(LazyTypeHint().from_yaml_file(
         loader=load_yaml_file,
         path="example.yaml",
         class_name="Sensors",
         comments_are=("above", "side"),
     ).to_string())
    

    Generate type hints like:

    from typing import List, TypedDict
    
    
    class SensorsSensorsDict(TypedDict):
        name: str
        sensor_type: str
        """Type of sensor used. NOTE: Only 3 are available."""
        location: str
        threshold: int
        """
        Maximum amount allowed.
    
        Units: [C].
        """
    
    SensorsSensors = List[SensorsSensorsDict]
    
    
    class Sensors(TypedDict):
        sensors: SensorsSensors
        """Collection of sensors."""
    

What makes it a different tool?

There are some tools that aim to perform something similar. Cattrs or pydantic require knowing the structure beforehand. Then, the developer is responsible for writing it. They are validation-oriented. This tool is more geared towards providing better type hints in an automated way and ensuring that the structure is accessed correctly. Although other tools such as Stubgen are able to generate .pyi files in an automated way, it might be required to edit the environment to indicate where these stub-based files are located.

All features

Main features:

  • Type hint any (nested) structure.
  • Validate structures by comparising its string representation via LazyTypeHintLive
  • Dictionaries can be type hinted as TypedDict, meaning that the IDE will have extra information about its underlying structures. Developer can therefore benefit from extra static analysis or autcomplete features.
  • Similarity based merge:
    • Equal (nested) structures will be detected as such and type hinted under the same type alias.
    • Similar structures such as dictionaries will be merged indicating which keys were found to be not mandatory or required.
  • Type hint structures within any given file (YAML, JSON...).
  • Document structures:
    • Specify a specific keyword within dictionaries that will be parsed and included as a docstring.
    • Some file format such as like YAML will also find and parse comments as docstrings.
  • Wide range of type hint based on strategies. The user can select at any time:
    • Which kind of container is prefered (Sequence/list)
    • How to type hint a tuple (either with fixed or non-fixed size)
    • The complexity of the type aliases to be created.
    • Dictionaries typed as Mapping, Dict or TypedDict
    • Minimum percentage of similarity between dicts to be merged.
    • Mutable or read-only based TypedDict.

Structures that can be type hinted:

  • Sequences: list, tuples
  • Sets: sets, frozensets
  • Dictionaries: dict, MappingProxyType
  • Pandas DataFrame: Full support for string-based columns and MultiIndex columns
  • Simple built-in types: bool, int, float, range, slice, None, str
  • Callables: lambdas, functions, staticmethods, classmethods, built-in functions
  • Module types
  • IOBase
  • Iterators
  • Custom objects: instances and classes

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lazy_type_hint-2.1.0.tar.gz (36.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lazy_type_hint-2.1.0-py3-none-any.whl (52.9 kB view details)

Uploaded Python 3

File details

Details for the file lazy_type_hint-2.1.0.tar.gz.

File metadata

  • Download URL: lazy_type_hint-2.1.0.tar.gz
  • Upload date:
  • Size: 36.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.10.11 Windows/10

File hashes

Hashes for lazy_type_hint-2.1.0.tar.gz
Algorithm Hash digest
SHA256 05f037b706071d6e1e74efefeb6948568404bff5024e168a8305bbe3782ba613
MD5 310df17ee06be2386ed5520dfbaef180
BLAKE2b-256 63c719fa76c70466be9f0210306046f1bc338d502468e026f1b21f2e945ab838

See more details on using hashes here.

File details

Details for the file lazy_type_hint-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: lazy_type_hint-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 52.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.10.11 Windows/10

File hashes

Hashes for lazy_type_hint-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 47ff599e93b2873220e822aaab0d2b470300d64875845ac63c5637684f398fad
MD5 69e41ddfb2173034ccbed1132e010b0f
BLAKE2b-256 05baffe86c5fa7e0b7b46ff5c4bac8ea614bf69578711e46b82d49d42c960bd3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page