Python default type in class type arguments

Viewed 1492

I'm trying to use generic type hints in python, however I'm not sure if a behaviour I want is possible or not. I've done a lot of reading on the type hints documentation, but cannot find what I'm looking for.

I want to be able to specify class type arguments with default types if the type isn't defined. For instance, I would imagine the code would look something like this.

T = TypeVar('T')
S = TypeVar('S')
class Attribute(Generic[T, S=int]):
    ...

class FooBar:
    a: Attribute[str, str]
    b: Attribute[str]

So in this case type S would default to int if it is not specified in a type hint. I am also happy with a solution which uses metaprogramming to make this possible.

1 Answers

The whole idea behind generic types stems from statically-typed languages (eg. Scala or Java) and it is to allow flexibility for types when defining code, and prevents unnecessary excessive overloading for functions (which is not needed in Python being a dynamically-typed language). Hence defining default or fallback types kind of deviates from the concepts of generic altogether. With that being said, I see that the Union[] is a better fit to answer your question.

If you would like to combine that with generic types (which does not make much sense given the logic behind generics), you can do something like:

from typing import Union, TypeVar

T = TypeVar('T')


def foo(var: Union[T, str]):
    if var:
        return "boo"


res = foo("bar")
print(res)

However, I suggest that when defining your code, try to be specific and strict when possible regarding types, and to define better generics. That can be accomplished by defining more strict generic/abstract types:

T = TypeVar('T')  # Can be anything
A = TypeVar('A', str, bytes)  # Must be str or bytes 

The latter will allow you to remain generic,with slightly more control over your types.

Related