For this particular use case, shouldn’t you just set the default value in the function definition or am I missing something?
Def myfunc(foo=“Bar”):
pass Def myfunc(foo=“Bar”):
passedit
Nevermind, I see what you mean. Yes, it would be equivalent, but it can be used in other scenarios. This was just the one I thought of.
grouped = {}
for (key, value) in ungrouped:
group = new.setdefault(key, [])
group.append(value)
defaultdict(list) would make it even shorter, but setdefault() is more general, as it makes it possible to have a "default" value that depends on the key itself.defaultdict combined with late-binding closures also allows to define nested dictionaries :
nested_dict = lambda: defaultdict(nested)
nested = nested_dict()
nested[0][1][2] = "value" foo = 123
def myfunc(foo="bar"):
global foo # problem! foo = 123
def lol(foo="bar"):
print(globals()["foo"], foo)
That will output "123 bar". But it's terrible!Your example is a SyntaxError, it doesn't even compile:
In [1]: def myfunc(foo="bar"):
...: global foo
Input In [1]
global foo
^
SyntaxError: name 'foo' is parameter and globalThat's why I said nonlocal or global ;)