Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Default argument
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Evaluation== For every function call default argument values must be passed to the called function. If a default argument value contains side-effects, it is significant when those side effects are evaluated β once for the entire program (at parse time, compile time, or load time), or once per function call, at call time. [[Python (programming language)|Python]] is a notable language that evaluates expressions in default arguments once, at the time the function declaration is evaluated. If evaluation per function call is desired, it can be replicated by having the default argument be a [[sentinel value]], such as <code>None</code>, and then having the body of the function evaluate the default value's side effects only if the sentinel value was passed in. For example: <syntaxhighlight lang="python"> import random def eager(a=random.random()): return a x = eager() y = eager() assert x == y def lazy(a=None): if a is None: a = random.random() return a x = lazy() y = lazy() assert x != y </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)