0

Is there a way to explicitly state an argument to a function in python should be an array of some custom class?

i.e.

I can write the following function to enforce the type of the args

def foo_bar(foo: str, bar: int):
    print("foo bar stuff")

But what if I want an argument to be an array of a custom class

class foobar():
    def __init__(self):
    ...

def foo_bar(foo: str, bar: int, array_of_foobar: [foobar]):
    print("foo bar stuff")

Is there a syntax to ensure the variable "array_of_foobar" is an array of the proper type?

To take it a step further, what if I have classes derived from class foobar() using AbstractBaseClass. Can I ensure the array if of type foobar, or derived from type foobar?

  • what do you mean by "array"? – juanpa.arrivillaga Aug 03 '23 at 19:05
  • "I can write the following function to enforce the type of the args" No, no you cannot. Those are type annotations. they are not enforced at runtime. This is *crucial* to understand. You can do `foo_bar(42, "baz")` and it will run with no problem – juanpa.arrivillaga Aug 03 '23 at 19:05
  • So what you want is `list[foobar]` (note, these are **lists** not arrays, array in Python generally refers to a `numpy.ndarray` or possibly a standard library `array.array`). Note, `list` is invariant in its type parameters, if you want covariance, you can use Sequence. Finally, to reiterate, none of this will be enforced at runtime unless *you* explicitly do that in the code (either by writing it yourself or using a library that does that) – juanpa.arrivillaga Aug 03 '23 at 19:12
  • Aahh I see, thank you – user21113865 Aug 03 '23 at 19:18

0 Answers0