(Assuming that) we all know what a python function is; I want to show some hacks that might help you.
(1) Optional parameters
def hi(name, age=18):
print(f"Hi {name} who is {age} years old!")
Here, when calling this function, you don't have to give a value to the age parameter, as it will default to 18. However giving a value to age will override the default value.
hi("Mahdi")
# >>> Hi Mahdi who is 18 years old!
hi("Magdi", 25)
# >>> Hi Magdi who is 25 years old!
Note: optional arguments/parameters must come at the end, so this won't work:
def hi(age=14, name):
print(f"Hi {name} who is {age} years old!")
hi(15, "Mohamed")
# >>> Syntax Error: non-default argument follows default argument
It's a good practice to let the default values None
.
(2) You can write parameters in a different order
Take a look at this function:
def salut(fromPerson, toPerson):
print(f"Hi from {fromPerson} to {toPerson}")
salut("Magdi", "Shady")
# >>> Hi from Magdi to Shady
This is also valid:
salut(toPerson="Shady", fromPerson="Magdi")
# >>> Hi from Magdi to Shady
It prints the same result as before. This feature is kinda cool, and it improves readability; even if you still write them in order.
Ok, that's good for now. Hope I helped you know something new, or clarified it. See you soon!
Top comments (4)
Heh, nice post!
btw to continue the topic, there are such things as
*args, **kwargs
, which are especially useful in decorators or wrappers, it can intercept all the arguments you pass, and give it as a list and dict respectivelyAlso there is a cool trick with star operators when you pass arguments to the func, example:
Also, star can be used to have "keyword-only" arguments, example:
BUT!
I would not recommend to overuse
*args, **kwargs
in your regular function, though it's flexible, since you can pass anything you need from outside to the function, but any minor typo or change can break all the things.NOTE
Some of things work only on python3+
Thanks for sharing! Really good tricks!
Cool post that has helped me reviewing function arguments.
giphy.com/gifs/VI9Q3ZzkOgB0urXE82/...
Thanks!