DEV Community


Posted on

Python: Fun Function Facts

(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 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!

Discussion (4)

egorblagov profile image
Egor Blagov

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 respectively

Also there is a cool trick with star operators when you pass arguments to the func, example:

def example(a, b, c='default'):
    print("a is {}, b is {}, c is {}".format(a,b,c))

example_args = {
    'a': 1,
    'b': 2



# or 

network_info = {
    'my_ip': "",
    'host_ip': "",
    'info': "Some info",
    'unused_argument': 'Some unused thing'

print('''Your ip is {my_ip}, you are trying
    to reach the host {host_ip},
    info: {info}'''.format(**network_info))

Also, star can be used to have "keyword-only" arguments, example:

def a(a, *, b):
    print(a, b)

# a(1, 2) -- TypeError: a() takes 1 positional argument but 2 were given
# a(1) -- TypeError: a() missing 1 required keyword-only argument: 'b'
# a(1, b=2) -- ok


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.


Some of things work only on python3+

doublepicebs profile image
Doublepicebs Author

Thanks for sharing! Really good tricks!

oxy_oxide profile image
Hamza Hesham

Cool post that has helped me reviewing function arguments.

doublepicebs profile image
Doublepicebs Author