Skip to main content

Automate type hint generation in an easy way.

Project description

LazyTypeHint

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

pip install lazy-type-hint

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:

    Imagen 1 Imagen 2
    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.
  • 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
  • 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.0.3.tar.gz (34.4 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.0.3-py3-none-any.whl (49.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: lazy_type_hint-2.0.3.tar.gz
  • Upload date:
  • Size: 34.4 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.0.3.tar.gz
Algorithm Hash digest
SHA256 faf0978241244b4b311a0f07b03ea554bcbbf895e08899039fdd0fdd930a448b
MD5 5d49f9584ed0db039cf8eddb3a0dfc8c
BLAKE2b-256 37ca0dea7f1e51c5b670aaaee989f05752e5d08efee74fc5c94e22a7e963be9c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: lazy_type_hint-2.0.3-py3-none-any.whl
  • Upload date:
  • Size: 49.1 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.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 1b7350f27f6dcb152d269547f7e59f570b2046460e2ab5cff01fada591cf9c92
MD5 afe4a9604ffb203d3c0aecd2973cfbc6
BLAKE2b-256 972b2df4a17c74e439eed83a28bdec8ee8acf771aca59fb3df78dab25a3ebe52

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