loading...

Python: Fun Function Facts

doublepicebs profile image Doublepicebs ・1 min read

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

Posted on by:

doublepicebs profile

Doublepicebs

@doublepicebs

Programmer and Designer. Self-taught Frontend Web and Python programmer.

Discussion

markdown guide
 

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
}

if SOME_CONDITION:
    example_args.update(c=20)

example(**example_args)


# or 

network_info = {
    'my_ip': "192.168.0.1",
    'host_ip': "192.168.0.100",
    '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

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!