DEV Community

Discussion on: Python: Fun Function Facts

Collapse
 
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
}

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+

Collapse
 
doublepicebs profile image
Doublepicebs

Thanks for sharing! Really good tricks!