0

I have the following function declaration:

def set_data(obj=None, name='delp', type=None):

Is there a python shortcut, where type is equal with 'name' value(default r passed) if is None ?

user3541631
  • 3,686
  • 8
  • 48
  • 115
  • 2
    Don't use `reserved words`, for your own sake (and probably everyone else working with your code), please :) – han solo Feb 20 '19 at 16:26

1 Answers1

5

The usual idiom is:

def set_data(obj=None, name='delp', type=None):
    if type is None:
        type = name

(But don't actually use type as a variable name, it'll mask the built in function as described here: Is it safe to use the python word "type" in my code?)

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • It could be just `type = type or name`. – Sraw Feb 20 '19 at 16:29
  • 1
    @Sraw note that this will assign the default if the variable is **any** false-y value, not just `None` – Phydeaux Feb 20 '19 at 16:30
  • 2
    Sraw - that's not identical in behavior. The empty string is not `None` but it is false, just for one example. If you want to be as concise as possible, a conditional expression (https://docs.python.org/3/reference/expressions.html#conditional-expressions) is one alternative. – Peter DeGlopper Feb 20 '19 at 16:31
  • @PeterDeGlopper Correct, but as here type seems to be a string. And there are only two kinds of false values: empty string or `None`. It could be enough. Although I admit it is not enough for many other situations. – Sraw Feb 20 '19 at 16:32
  • 1
    @Sraw an equivalent one liner would be `type = name if type is None else type` – r.ook Feb 20 '19 at 16:36