简体   繁体   中英

What's a more pythonic way to write this function declaration

This is parred down to the most basic elements for the sake of brevity. I understand that the below is redundant as written, but I digress.

I want to know if there's a smarter, more concise way to write this

def create_action(context, verb, actor = None, target = None, permission_level = None):
    action = Action(context = context, verb = verb, actor = actor, target = target, permission_level = permission_level)

As you can see, two required arguments, a handful (or potentially more) optional ones overloaded.

What's a better way to write this so that I am not slinging around these keywords?

Use unpacking of arguments :

def create_action(*args, **kwargs):
    action = Action(*args, **kwargs)

First off, remove spaces between the parts of default args. You also probably don't need to use keyword arguments for the call to Action() eg

def create_action(context, verb, actor=None, target=None, permission_level=None):
    action = Action(context, verb, actor, target, permission_level)

That's the conventional Python style for using default arguments.

Frankly, I don't see why this function is necessary at all. it doesn't return anything (I guess you just forgot to return action, and everything it accomplishes ought to be done in the __init__ method for the Action class (I assume it's a class), eg

class Action(object):
    def __init__(context, verb, actor=None, target=None, permission_level=None):
        # Do something

For brevity, I wouldn't write the function at all and just use default arguments in the __init__ method of the class.

If you want to:

  • ensure context and verb are explicitly passed
  • only pass legitimate args

You can do something like this.

optional = ('actor', 'target', 'permission_level')
def create_action(context, verb, **opt):
  args = dict([(k, opt.get(k, None) for k in optional])
  action = Action(context, verb, **args)

or this if you want to pass them all as named arguments.

optional = (('actor', None), ('target', None), ('permission_level', None))
required = ('context', 'verb')
def create_action(*a, **kv):
  req = zip(required, a)
  opt = [(t[0], kv.get(t[0], t[1])) for t in optional]
  action = Action(**dict(req + opt))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM