sergzach
sergzach

Reputation: 6764

Passing as kwargs, reading as args - a special or temporary feature?

Sometimes it's convenient to pass kwargs to a function which receives args.

For example:

def login( user, password ):
    ...

def write_message( author, to_user, msg ):
    ...

def http_response( action, params ):
    return globals()[ action ]( **params )

# client calls 
# http_response( 'login', { 'user': "sergzach", 'password': "PASS123" } )

In this schematic example, we receive information from the client and call a function whose name is equal to the variable action passed in params. If our client knows the protocol {necessary 'keyword' arguments such as user, password for login() and author, to_user, msg for write_message()} then our pythonic code could be short, elegant and safe.

Is it a special (documented) or random feature?

Upvotes: 0

Views: 66

Answers (2)

shx2
shx2

Reputation: 64328

Your example is guaranteed to work in python. In python, you can always choose to pass named parameters as keyword arguments.

As already pointed out in the comments, this approach is potentially not safe (calling a function by a user-provided name). So pay extra care if doing so (the comments also include some good suggestions for safety).

Other than that, I'm not sure I understand what exactly you mean by "a random feature"?..

Upvotes: 1

Kevin
Kevin

Reputation: 30161

Python distinguishes between arguments and parameters.

A parameter is something you list in the function definition:

def foo(bar, baz=default, **quux):
    pass

An argument is something you pass to a function when you call it:

result = foo(bar, baz, **quux)

Given the above function definition, Python allows any of these calls:

foo(bar, baz, quux1=quux1, quux2=quux2)
foo(*(bar, baz), quux1=quux1, quux2=quux2)
foo(**{'bar': bar, 'baz': baz, 'quux1': quux1, 'quux2':quux2})

They're all perfectly legal and do the same thing. That is, they all pass the same arguments.

Upvotes: 2

Related Questions