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 ?

1
  • 2
    Don't use reserved words, for your own sake (and probably everyone else working with your code), please :) Commented Feb 20, 2019 at 16:26

1 Answer 1

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?)

Sign up to request clarification or add additional context in comments.

5 Comments

It could be just type = type or name.
@Sraw note that this will assign the default if the variable is any false-y value, not just None
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 (docs.python.org/3/reference/…) is one alternative.
@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 an equivalent one liner would be type = name if type is None else type

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.