-
Notifications
You must be signed in to change notification settings - Fork 5.3k
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
Sample code for the article on closures #581
Conversation
python-closure/closure.py
Outdated
|
||
def outer_func(): | ||
name = "Pythonista" | ||
return lambda name=name: print(f"Hello, {name}!") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@lpozo Actually, I just realized this is the wrong syntax for a lambda expression. This is the correct one:
return lambda name=name: print(f"Hello, {name}!") | |
return lambda name: print(f"Hello, {name}!") |
Unfortunately, this mistake is also present in the tutorial text.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It doesn't work if we don't set the argument:
>>> def outer_func():
... name = "Pythonista"
... return lambda name: print(f"Hello, {name}!")
...
...
>>> func = outer_func()
>>> func()
Traceback (most recent call last):
File "<input>", line 1, in <module>
func()
TypeError: outer_func.<locals>.<lambda>() missing 1 required positional argument: 'func'
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The correct syntax is:
>>> def outer_func():
... name = "Pythonista"
... return lambda: print(f"Hello, {name}!")
...
...
>>> func = outer_func()
>>> func()
Hello, Pythonista!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@lpozo There's one small detail to fix in the lambda expression example (same in the tutorial text.)
Where to put new files:
my-awesome-article
How to merge your changes: