0

Can this be done in one line? Something that looks like this data['x'] = (x if x else "") (except doesn't raise an exception)

Otherwise I often end up doing the following:

try: data['x'] = x
except: data['x'] = ""

or for multiple keys initializing with empty values: i.e.

data['x'], data['y'] = [], []
7
  • 1
    Why would data['x'] = x raise an exception? You mean x might not be set? Generally, you'd avoid that kind of situation. Commented Jun 19, 2014 at 18:04
  • 2
    using globals().get('x', '') ? or locals().get('x', '') Commented Jun 19, 2014 at 18:04
  • @MartijnPieters, it's probably a NameError Commented Jun 19, 2014 at 18:05
  • 1
    @AdamWagner: yeah, I see that. A case of why not just set x = '' and be done with it. Commented Jun 19, 2014 at 18:05
  • 1
    @user3467349, you should generally know if a var exists. And as Martjin points out, you could just set the value ahead of time to some default value, so you don't get an exception. Commented Jun 19, 2014 at 18:07

1 Answer 1

2

As others have pointed out on comments, using probably unset variables is poor form, but if you insist, Luis Masuelli's comment should do the trick:

data['x'] = locals().get('x','')  # or globals, depending on the scope you need
Sign up to request clarification or add additional context in comments.

2 Comments

I don't see the reason for generalizing 'all possible use cases' to poor form. But that does work, thanks.
Sure, there are exceptions to everything, but generally it would suggest a flawed design somewhere on the line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.