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, 开发者_如何学Goactor = 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()
e.g.
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), e.g.
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
andverb
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))
精彩评论