How to write an empty Dictionary parameter for safe in gds?

Godot Version

4.4

Question

Hello, I’m working with a function with Dictionary and other type of parameters. For some reason I need to make the Dictionary parameter empty, like:

func test(p1: int, p2: Dictionary = {}) -> void:
    pass

# so can be used like
test(3, {'abc': 123})
# and also
test(123)

I know the {} value of dict is not safe in python, but is this ok in gdscript? Or maybe use like:

# better?
const EMPTY_DICT = {}
func test(p1: int, p2: Dictionary = EMPTY_DICT) -> void:
    pass

# I know it's wrong below, but that's somehow I want directly.
# and union type is not allowed: Dictionary | null
func test(p1: int, p2: Dictionary = null) -> void:
    pass

So, I want to keep my type notations for parameters, and the same time make the Dictionary default value empty in a safe way, please give me some advice, thank you!

I don’t know of any problem with {} in GDScript, I always use it as the default value for a dictionary and then check .size() == 0 to see if it’s empty.

What do you mean {} is not safe in python?

What are you trying to protect against, and how do you plan to use this?

Dictionary will generate errors if you try to read the value for a key that it doesn’t contain. The fix for this is the .has() method:

# hacky example

func get_val_or_default(d: Dictionary, key: String, def: Variant) -> Variant:
    if d.has(key): return d.[key]
    return def

{} is passed by reference in python and Godot, where most base types are copied when given to a function. In python the default-argument dictionary is kept between calls, Godot does not seem to do this luckily, but it’s a good habit to avoid defaults on reference-types.

def f(key, value, my_dict={}):
    my_dict[key] = value
    return my_dict

print(f('a', 1)) # prints: { 'a': 1 }
print(f('b', 2)) # prints: { 'a': 1, 'b': 2 }

example from stack overflow

3 Likes

Thank you, I overthought it, and thanks to everyone else!