-2

I've got this:

def gradient_descent(
  ...
  model_class: Type[Model],
  J: Callable[[np.ndarray, model_class], float],
  ...
):

I want this function to take in a class, and also a function that accepts an instance of that class. However, this gives me the error Name "model_class" is not defined.. I'm assuming that's because mypy doesn't have access to model_class at typechecking time.

Is there any way to achieve this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Eli Rose
  • 6,788
  • 8
  • 35
  • 55

1 Answers1

1

I think what you're looking for is a generic type, e.g.:

T = TypeVar('T', bound=Model) 

def gradient_descent(
  ...
  model_class: Type[T],
  J: Callable[[np.ndarray, T], float],
  ...
):
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Hmm, when I run this I get "'TypeVar' can only have a single constraint." The example gives two constraints, `TypeVar('T', str, bytes)`. It looks like it's functioning as a union type of the two? As opposed to declaring that type T is a subclass of Model. – Eli Rose Jan 23 '20 at 14:48
  • @EliRose--REINSTATEMONICA ah yes; fixed, see e.g. https://stackoverflow.com/a/50185096/3001761 – jonrsharpe Jan 23 '20 at 14:52