DEV Community

Discussion on: Python: Fun Function Facts

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!