14

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.

0

2 Answers 2

13

I think you're gonna have to wait till Python 3.13 if I'm understanding this correctly.

PEP 696 – Type defaults for TypeVarLikes | peps.python.org

Update so it's not a link-only answer. If it gets implemented it would look something like this for you.

T = TypeVar('T') S = TypeVar('S', default=int) class Attribute(Generic[T, S]): 
Sign up to request clarification or add additional context in comments.

2 Comments

This is available with typing-extensions package.
As it is written, this is a link-only answer. Please edit to show how the new features introduced by the PEP solve OP's problem.
-5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.