Static Typing and for iterators

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By brazmogu

So, GDScript allows static typing, which means defining the type of a variable, a very useful feature for, among other things, completion and reference.

Problem is, it seems it cannot be used to define the type of elements in an array (arrays, like in Python, can contain any type of data) and because of that I can’t enjoy the advantages of static typing when iterating through an array.

Is there anyway to do something like this

for i in range(len(someArray)):
    var iterator:someType = someArray[i]
    [...]

But instead as something like

for iterator:someType in someArray:
    [...]

You can’t force the assignment of types in a ‘for’ loop, as each element the ‘for’ keyword loops over already has a different type.

asetyowatir | 2020-10-26 03:29

Well… they can, but shouldn’t I be able to declare to the code that I expect them not to?

brazmogu | 2020-11-04 22:33

Not really, as far as I’ve been able to determine. Like many dynamic languages, GDScript does not differentiate between the collection of arbitrary types (GDScripts Array), collections of fixed types (like NumPy’s ndarray), and collections of a class or below. I had to code around to get array’s of resources to auto populate with the right types and it still seems buggy.

CharlesMerriam | 2020-11-05 07:15

:bust_in_silhouette: Reply From: CharlesMerriam

This is a place where the static typing makes things harder to read. You probably want:

for thing in SomeArray:
     assert (Util.what(thing) == "expected Class")

where Util is the usual static library people write, using typeof and get_type

I don’t really want to assert it as much as I want the code to know what type my iterator is so I can use completion and other type checking features.

Like, I could do

for thing in someArray:
    var _thing:someType = thing
    [...]

But should that mandatory extra step exist?

brazmogu | 2020-11-04 22:32

Yes, it should. You are looking for Python’s __iter__/__next__ interface. GDScript gets enough extra complexity from gaming concepts (Scenes, Resources, signals, etc.) and chose not to allow the bells and whistles.

Perhaps we should bitch about language design over Zoom?

CharlesMerriam | 2020-11-05 07:21