Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set "array of strings" as a type for a parameter in a function?

I want to check right at the passing of the arguments to a function if the argument is an array of strings.

Like setting a type to the parameter of the function to "array of string". But I don't want to loop through the array looking for none-string elements.

Is there a type like this?


2 Answers

You can use typing for recent python version (tested on 3.9), as suggested by @Netwave in the comments:

def my_function(a: list[str]):
  # You code

Which will lint as expected:

pycharm linting example

like image 157
KawaLo Avatar answered Jan 01 '26 17:01

KawaLo


>>> isinstance(["abc", "def", "ghi", "jkl"], list)
True
>>> isinstance(50, list)
False

You could use this inside your function in order to check if your argument is a list.

like image 28
HLupo Avatar answered Jan 01 '26 18:01

HLupo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!