-2

In Java, if I want to increase a variable A, and set B equal to C, I can do it one statement as follows:

B = C + A - A++;

Python, unfortunately, does not support assignment within literals. What is the best way to mimic this kind of behavior within the language of Python? (with the intention of writing code in as few statements as possible)

Let me set something straight: I am not interested in writing code that is readable. I am interested in writing code with as few statements as possible.

One trivial example of one case where this would work would be to write a class that holds an int and has methods such as plus_equals, increment, etc.

Will Sherwood
  • 1,484
  • 3
  • 14
  • 27

2 Answers2

4

In the global namespace, you can do something really ugly like this:

B = globals().__setitem__('A', A + 1) or C

Unfortunately for you (and probably fortunately for the person who has to read the code after you've written it), there is no analogous way to do this with a local variable A.

mgilson
  • 300,191
  • 65
  • 633
  • 696
-1

Let me set something straight: I am not interested in writing code that is readable. I am interested in writing code with as few statements as possible.

Well, if that's your goal, wrap your entire program in a giant exec:

exec """
<your program here>
"""

Bam, one statement.

user2357112
  • 260,549
  • 28
  • 431
  • 505