Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typed Dictionaries can allow different typed keys/values when using operator[] #96772

Closed
aaronp64 opened this issue Sep 9, 2024 · 3 comments · Fixed by #96797
Closed

Typed Dictionaries can allow different typed keys/values when using operator[] #96772

aaronp64 opened this issue Sep 9, 2024 · 3 comments · Fixed by #96797

Comments

@aaronp64
Copy link
Contributor

aaronp64 commented Sep 9, 2024

Tested versions

Latest master v4.4.dev.custom_build [2124995]

System information

Windows 10

Issue description

Adding to a typed dictionary using operator[] allows adding keys/values of different types, if the types aren't known until run time, or if the typed dictionary is passed into a function that takes an untyped dictionary. In both cases, using get_or_add catches the difference and gives an error.

Steps to reproduce

Create a new project, and add code below to main scene:

func _ready():
	var dictionary : Dictionary[Node, Node] = { }
	# dictionary["test1"] = 1 # Gives error in editor
	# dictionary.get_or_add(get_key(), get_value()) # Type check error
	dictionary[get_key()] = get_value()
	_test_dictionary_func(dictionary)
	print(dictionary)

func _test_dictionary_func(d : Dictionary):
	# d.get_or_add("test2", 2) # Type check error
	d["test2"] = 2

func get_key():
	return "test1"

func get_value():
	return 1

This prints { "test1": 1, "test2": 2 } without giving any errors

Minimal reproduction project (MRP)

N/A

@SBNovaScript
Copy link

As GDScript is a gradually typed language, is there a need to implement this type inference? Would we expect this dictionary's type to not be cast to the untyped dictionary? As get_or_add verifies types during runtime, it might make more sense to prefer that when potentially using mixed types. I'm all for increased type inference accuracy though.

@dalexeev
Copy link
Member

CC @Repiteo

@Repiteo
Copy link
Contributor

Repiteo commented Sep 10, 2024

Oh shoot, good catch! This was an erroneous regression in one of the rebases of the typed dictionary PR. Making a fix and putting up a testcase to make sure this won't happen again 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants