2

I have a quite long statement:

if LongClassName.results[variable1][longerVariable2][variable3] == 0:
   LongClassName.results[variable1][longerVariable2][variable3] = 42

As one can clearly see, there is quite a lot of repetition in this code (the same expression is used in the conditional and in its body). Is there a way of simplifying it? In C++ I could use references, like this:

auto &ref = LongClassName.results[variable1][longerVariable2][variable3];
if (ref == 0) {
    ref = 42;
}

What is the Pythonic way of simplifying this expression?

martineau
  • 119,623
  • 25
  • 170
  • 301
lukeg
  • 4,189
  • 3
  • 19
  • 40
  • declaring, referencing, and setting a variable is (mostly) language agnostic > https://www.pythonforbeginners.com/basics/python-variables – RandomUs1r Oct 19 '18 at 21:00
  • @Robin (and @RandomUs1r): Python doesn't have references, so the `ref = 42` wouldn't work with what you're suggesting. – martineau Oct 19 '18 at 21:00
  • As stated [in this answer](https://stackoverflow.com/a/3106752/10484131) it's the Pythonic way to be explicit. – Felix Oct 19 '18 at 21:00
  • @martineau - sorry, yeah, you're right. I hadn't noticed that an actual assignment was going on. – Robin Zigmond Oct 19 '18 at 21:03

3 Answers3

2

You can stop and grab the reference a level above this:

partial_ref = LongClassName.results[variable1][longerVariable2]
if partial_ref[variable3] == 0:
   partial_ref[variable3] = 42

That's not particularly Pythonic, but it's the closest to your original C++ code.

user2357112
  • 260,549
  • 28
  • 431
  • 505
Prune
  • 76,765
  • 14
  • 60
  • 81
2

You could shorten it to some degree like this:

container = LongClassName.results[variable1][longerVariable2]
if container[variable3] == 0:
   container[variable3] = 42

Python doesn't have totally general references like C++ does, so this creates a shorter name for the container of variable3 and uses its name in subsequent statements.

martineau
  • 119,623
  • 25
  • 170
  • 301
-1
x = LongClassName.results[variable1][longerVariable2]
if x[variable3] == 0:
   x[variable3] = 42

that works but doesn't seem very elegant.

anon
  • 77
  • 2
  • @jasonharper: Poster changed they're answer since you posted your comment—so it's now like the others and will actually work. – martineau Oct 19 '18 at 21:12