TypeVar "Ts" appears only once in generic function signature #3953
Replies: 3 comments 48 replies
-
We can simplify this. This code, from typing import TypeVar
T = TypeVar('T')
def foo(x: T):
print('hi') produces same kind of error. The main value of generic type is when you will use it in multiple places. Typically if it's used as both input type and part of return type. It could also just appear several times in input type. It can also be fine if type variable is under class scope. But a bare function with a single type variable is rarely useful. If you don't care what type is you should just use object. For your code, def foo(*args: object):
for ndx, arg in enumerate(args):
print(f'Arg{ndx}: {arg}, {type(arg)}') is recommended way to type it. |
Beta Was this translation helpful? Give feedback.
-
You might as well use this phrase as the error message - it's just as informative, but far more honest. Certainly works better than suggesting to use |
Beta Was this translation helpful? Give feedback.
-
I want to use TypeVar to declare a generic type that would be extended in subclass like a config class with extra fields. # foo.py
class Foo:
a: int
b: int # bar.py
from abc import ABC, abstractmethod
from typing import TypeVar
from foo import Foo
FooBase = TypeVar("FooBase", bound=Foo)
class Bar(ABC):
@abstractmethod
@classmethod
def init_foo(cls, foo: FooBase):
# ~~~~~~~
# TypeVar "FooBase" appears only once in generic function signature
# Use "Foo" instead [reportInvalidTypeVarUse]
pass # subbar.py
from bar import Bar
from foo import Foo
class SubFoo(Foo):
c: str
class SubBar(Bar):
@classmethod
def init_foo(cls, foo: SubFoo):
return super().init_foo(foo) But if I replace
|
Beta Was this translation helpful? Give feedback.
-
Can someone please explain to me what this error means?
For reference, I am attempting to type hint
*args
as suggested in PEP 646 and am getting this error on the pyright playground at line 7.Beta Was this translation helpful? Give feedback.
All reactions