Search code examples
pythontypescripttype-hinting

Add type hints to a python package similar to how TypeScript can use a .d.ts file


I'm using a library that is a little old and doesn't have Python type hints.

Since this isn't my library, I can't simply just type hints in. With TypeScript, there is a concept of using a .d.ts file that goes along side the .js file. This provides typing information without modifying to original code. Is there some way in python that this could be implemented?

So far the only thing I've come up with is to extend the classes without type hints and make a super call to them. Unless I'm mistaken, this would require wrapping every single function/class in the original code to function, instead of just not having a type hint for a missing one in the wrapper class.

class The_Class_I_Want_To_Use:
    def foo(self, foo, bar):
        ...

class My_TypeHint_Wrapper(The_Class_I_Want_To_Use):
    ...
    def foo(self, foo: str, bar: str) -> bool:
        super().foo(foo, bar)

Solution

  • You're looking for stubs. You will also want to run mypy static type checker to make use of stubs.

    Stubs are essentially files that contain type hints and function signatures without any implementation details.

    So, for example, you have a module called example_module that contains ExampleClass with no type annotations specified.

    # example_module.py
    
    class ExampleClass:
        def foo(self, foo, bar):
            return foo == bar
    
    1. Create a new file called example_module.pyi in the same directory. The .pyi extension indicates that this is a Python stub file.
    2. Inside the example_module.pyi file, declare the ExampleClass with methods signatures of the same name and parameters as the original class, but without any implementation details.
      # example_module.pyi
      
      class ExampleClass:
          def foo(self, foo: str, bar: str) -> bool:
              ...
      

    Now you should be able to check the type annotations by running mypy against the modules where ExampleClass.foo is used.
    Also, your IDE of choice should be able to highlight type errors related to the annotated code.