Does python reuse repeated calculation results?Calling an external command in PythonWhat are metaclasses in Python?What does the “yield” keyword do?Does Python have a ternary conditional operator?What does if __name__ == “__main__”: do?“Least Astonishment” and the Mutable Default ArgumentPython progression path - From apprentice to guruDoes Python have a string 'contains' substring method?Why is reading lines from stdin much slower in C++ than Python?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

Using 4K Skyrim Textures when running 1920 x 1080 display resolution?

Where does the image of a data connector as a sharp metal spike originate from?

How to calculate Limit of this sequence

Does the DOJ's declining to investigate the Trump-Zelensky call ruin the basis for impeachment?

What is /dev/null and why can't I use hx on it?

Maintaining distance

Has Boris Johnson ever referred to any of his opponents as "traitors"?

Anonymous reviewer disclosed his identity. Should I thank him by name?

Is negative resistance possible?

Determine the Winner of a Game of Australian Football

How to catch creatures that can predict the next few minutes?

Search for something difficult to count/estimate

How to print variable value in next line using echo command

How is the speed of nucleons in the nucleus measured?

Why is the time of useful consciousness only seconds at high altitudes, when I can hold my breath much longer at ground level?

Has a hard SciFi story addressed launching from Venus and its high-density atmosphere, especially after 1967?

How to be productive while waiting for meetings to start

Why do many websites hide input when entering a OTP

Scorched receptacle

Bash-script as linux-service won't run, but executed from terminal works perfectly

How to get a smooth, uniform ParametricPlot of a 2D Region?

Non-electric Laser

Should I be able to see patterns in a HS256 encoded JWT?

Does it require less energy to reach the Sun from Pluto's orbit than from Earth's orbit?



Does python reuse repeated calculation results?


Calling an external command in PythonWhat are metaclasses in Python?What does the “yield” keyword do?Does Python have a ternary conditional operator?What does if __name__ == “__main__”: do?“Least Astonishment” and the Mutable Default ArgumentPython progression path - From apprentice to guruDoes Python have a string 'contains' substring method?Why is reading lines from stdin much slower in C++ than Python?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









7















If I have an expression that I wish to evaluate in Python, such as the expression for 'r' in the code snippet below, will the Python interpreter be smart and reuse the subresult x+y+z, or just evaluate it twice? I'd also be interested to know if the answer to this question would be the same for a compiled language, e.g. C.



 x=1
y=2
z=3
r = (x+y+z+1) + (x+y+z+2)









share|improve this question






























    7















    If I have an expression that I wish to evaluate in Python, such as the expression for 'r' in the code snippet below, will the Python interpreter be smart and reuse the subresult x+y+z, or just evaluate it twice? I'd also be interested to know if the answer to this question would be the same for a compiled language, e.g. C.



     x=1
    y=2
    z=3
    r = (x+y+z+1) + (x+y+z+2)









    share|improve this question


























      7












      7








      7








      If I have an expression that I wish to evaluate in Python, such as the expression for 'r' in the code snippet below, will the Python interpreter be smart and reuse the subresult x+y+z, or just evaluate it twice? I'd also be interested to know if the answer to this question would be the same for a compiled language, e.g. C.



       x=1
      y=2
      z=3
      r = (x+y+z+1) + (x+y+z+2)









      share|improve this question














      If I have an expression that I wish to evaluate in Python, such as the expression for 'r' in the code snippet below, will the Python interpreter be smart and reuse the subresult x+y+z, or just evaluate it twice? I'd also be interested to know if the answer to this question would be the same for a compiled language, e.g. C.



       x=1
      y=2
      z=3
      r = (x+y+z+1) + (x+y+z+2)






      python interpreter interpreted-language






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 8 hours ago









      user189076user189076

      512 bronze badges




      512 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          4
















          You can check that with dis.dis. The output is:



           2 0 LOAD_CONST 0 (1)
          2 STORE_NAME 0 (x)

          3 4 LOAD_CONST 1 (2)
          6 STORE_NAME 1 (y)

          4 8 LOAD_CONST 2 (3)
          10 STORE_NAME 2 (z)

          5 12 LOAD_NAME 0 (x)
          14 LOAD_NAME 1 (y)
          16 BINARY_ADD
          18 LOAD_NAME 2 (z)
          20 BINARY_ADD
          22 LOAD_CONST 0 (1)
          24 BINARY_ADD
          26 LOAD_NAME 0 (x)
          28 LOAD_NAME 1 (y)
          30 BINARY_ADD
          32 LOAD_NAME 2 (z)
          34 BINARY_ADD
          36 LOAD_CONST 1 (2)
          38 BINARY_ADD
          40 BINARY_ADD
          42 STORE_NAME 3 (r)
          44 LOAD_CONST 3 (None)
          46 RETURN_VALUE


          So it won't cache the result of the expression in parentheses. Though for that specific case it would be possible, in general it is not, since custom classes can define __add__ (or any other binary operation) to modify themselves. For example:



          class Foo:
          def __init__(self, value):
          self.value = value

          def __add__(self, other):
          self.value += 1
          return self.value + other

          x = Foo(1)
          y = 2
          z = 3
          print(x + y + z + 1) # prints 8
          print(x + y + z + 1) # prints 9


          If you have an expensive function of which you would like to cache the result, you can do so via functools.lru_cache for example.



          On the other hand, the compiler will perform constant folding as can be seen from the following examples:



          >>> import dis
          >>> dis.dis("x = 'abc' * 5")
          1 0 LOAD_CONST 0 ('abcabcabcabcabc')
          2 STORE_NAME 0 (x)
          4 LOAD_CONST 1 (None)
          6 RETURN_VALUE
          >>> dis.dis("x = 1 + 2 + 3 + 4")
          1 0 LOAD_CONST 0 (10)
          2 STORE_NAME 0 (x)
          4 LOAD_CONST 1 (None)
          6 RETURN_VALUE





          share|improve this answer


































            3
















            No it will not. You can do this to see the compiled code:



            from dis import dis
            dis("r=(x+y+z+1) + (x+y+z+2)")


            Output:



             0 LOAD_NAME 0 (x)
            2 LOAD_NAME 1 (y)
            4 BINARY_ADD
            6 LOAD_NAME 2 (z)
            8 BINARY_ADD
            10 LOAD_CONST 0 (1)
            12 BINARY_ADD
            14 LOAD_NAME 0 (x)
            16 LOAD_NAME 1 (y)
            18 BINARY_ADD
            20 LOAD_NAME 2 (z)
            22 BINARY_ADD
            24 LOAD_CONST 1 (2)
            26 BINARY_ADD
            28 BINARY_ADD
            30 STORE_NAME 3 (r)
            32 LOAD_CONST 2 (None)
            34 RETURN_VALUE


            This is partially because Python is dynamically-typed. So the types of variables are not easily known at compile time. And the compiler has no way to know whether the + operator, which can be overloaded by user classes, could have any side effect at all. Consider the following simple example:



            class A:
            def __init__(self, v):
            self.value = v

            def __add__(self, b):
            print(b)
            return self.value + b

            x = A(3)
            y = 4
            r = (x + y + 1) + (x + y + 2)


            For simple expressions, you can just save the intermediate results to a new variable:



            z = x + y + 1
            r = z + (z + 1)


            For functions calls, functools.lru_cache is another option, as already indicated by other answers.






            share|improve this answer


































              0
















              No, python doesn't do that by default since it would use up too much memory, if you need python to preserve the result of a certain calculation for you, you need to implicitly tell python to do that, one way to do this would be by defining a function and useing functools.lru_cache docs:



              from functools import lru_cache

              @lru_cache(maxsize=32)
              def add3(x,y,z):
              return x + y + z

              x=1
              y=2
              z=3
              r = (add3(x,y,z)+1) + (add3(x,y,z)+2)





              share|improve this answer


























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );














                draft saved

                draft discarded
















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f58146860%2fdoes-python-reuse-repeated-calculation-results%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                4
















                You can check that with dis.dis. The output is:



                 2 0 LOAD_CONST 0 (1)
                2 STORE_NAME 0 (x)

                3 4 LOAD_CONST 1 (2)
                6 STORE_NAME 1 (y)

                4 8 LOAD_CONST 2 (3)
                10 STORE_NAME 2 (z)

                5 12 LOAD_NAME 0 (x)
                14 LOAD_NAME 1 (y)
                16 BINARY_ADD
                18 LOAD_NAME 2 (z)
                20 BINARY_ADD
                22 LOAD_CONST 0 (1)
                24 BINARY_ADD
                26 LOAD_NAME 0 (x)
                28 LOAD_NAME 1 (y)
                30 BINARY_ADD
                32 LOAD_NAME 2 (z)
                34 BINARY_ADD
                36 LOAD_CONST 1 (2)
                38 BINARY_ADD
                40 BINARY_ADD
                42 STORE_NAME 3 (r)
                44 LOAD_CONST 3 (None)
                46 RETURN_VALUE


                So it won't cache the result of the expression in parentheses. Though for that specific case it would be possible, in general it is not, since custom classes can define __add__ (or any other binary operation) to modify themselves. For example:



                class Foo:
                def __init__(self, value):
                self.value = value

                def __add__(self, other):
                self.value += 1
                return self.value + other

                x = Foo(1)
                y = 2
                z = 3
                print(x + y + z + 1) # prints 8
                print(x + y + z + 1) # prints 9


                If you have an expensive function of which you would like to cache the result, you can do so via functools.lru_cache for example.



                On the other hand, the compiler will perform constant folding as can be seen from the following examples:



                >>> import dis
                >>> dis.dis("x = 'abc' * 5")
                1 0 LOAD_CONST 0 ('abcabcabcabcabc')
                2 STORE_NAME 0 (x)
                4 LOAD_CONST 1 (None)
                6 RETURN_VALUE
                >>> dis.dis("x = 1 + 2 + 3 + 4")
                1 0 LOAD_CONST 0 (10)
                2 STORE_NAME 0 (x)
                4 LOAD_CONST 1 (None)
                6 RETURN_VALUE





                share|improve this answer































                  4
















                  You can check that with dis.dis. The output is:



                   2 0 LOAD_CONST 0 (1)
                  2 STORE_NAME 0 (x)

                  3 4 LOAD_CONST 1 (2)
                  6 STORE_NAME 1 (y)

                  4 8 LOAD_CONST 2 (3)
                  10 STORE_NAME 2 (z)

                  5 12 LOAD_NAME 0 (x)
                  14 LOAD_NAME 1 (y)
                  16 BINARY_ADD
                  18 LOAD_NAME 2 (z)
                  20 BINARY_ADD
                  22 LOAD_CONST 0 (1)
                  24 BINARY_ADD
                  26 LOAD_NAME 0 (x)
                  28 LOAD_NAME 1 (y)
                  30 BINARY_ADD
                  32 LOAD_NAME 2 (z)
                  34 BINARY_ADD
                  36 LOAD_CONST 1 (2)
                  38 BINARY_ADD
                  40 BINARY_ADD
                  42 STORE_NAME 3 (r)
                  44 LOAD_CONST 3 (None)
                  46 RETURN_VALUE


                  So it won't cache the result of the expression in parentheses. Though for that specific case it would be possible, in general it is not, since custom classes can define __add__ (or any other binary operation) to modify themselves. For example:



                  class Foo:
                  def __init__(self, value):
                  self.value = value

                  def __add__(self, other):
                  self.value += 1
                  return self.value + other

                  x = Foo(1)
                  y = 2
                  z = 3
                  print(x + y + z + 1) # prints 8
                  print(x + y + z + 1) # prints 9


                  If you have an expensive function of which you would like to cache the result, you can do so via functools.lru_cache for example.



                  On the other hand, the compiler will perform constant folding as can be seen from the following examples:



                  >>> import dis
                  >>> dis.dis("x = 'abc' * 5")
                  1 0 LOAD_CONST 0 ('abcabcabcabcabc')
                  2 STORE_NAME 0 (x)
                  4 LOAD_CONST 1 (None)
                  6 RETURN_VALUE
                  >>> dis.dis("x = 1 + 2 + 3 + 4")
                  1 0 LOAD_CONST 0 (10)
                  2 STORE_NAME 0 (x)
                  4 LOAD_CONST 1 (None)
                  6 RETURN_VALUE





                  share|improve this answer





























                    4














                    4










                    4









                    You can check that with dis.dis. The output is:



                     2 0 LOAD_CONST 0 (1)
                    2 STORE_NAME 0 (x)

                    3 4 LOAD_CONST 1 (2)
                    6 STORE_NAME 1 (y)

                    4 8 LOAD_CONST 2 (3)
                    10 STORE_NAME 2 (z)

                    5 12 LOAD_NAME 0 (x)
                    14 LOAD_NAME 1 (y)
                    16 BINARY_ADD
                    18 LOAD_NAME 2 (z)
                    20 BINARY_ADD
                    22 LOAD_CONST 0 (1)
                    24 BINARY_ADD
                    26 LOAD_NAME 0 (x)
                    28 LOAD_NAME 1 (y)
                    30 BINARY_ADD
                    32 LOAD_NAME 2 (z)
                    34 BINARY_ADD
                    36 LOAD_CONST 1 (2)
                    38 BINARY_ADD
                    40 BINARY_ADD
                    42 STORE_NAME 3 (r)
                    44 LOAD_CONST 3 (None)
                    46 RETURN_VALUE


                    So it won't cache the result of the expression in parentheses. Though for that specific case it would be possible, in general it is not, since custom classes can define __add__ (or any other binary operation) to modify themselves. For example:



                    class Foo:
                    def __init__(self, value):
                    self.value = value

                    def __add__(self, other):
                    self.value += 1
                    return self.value + other

                    x = Foo(1)
                    y = 2
                    z = 3
                    print(x + y + z + 1) # prints 8
                    print(x + y + z + 1) # prints 9


                    If you have an expensive function of which you would like to cache the result, you can do so via functools.lru_cache for example.



                    On the other hand, the compiler will perform constant folding as can be seen from the following examples:



                    >>> import dis
                    >>> dis.dis("x = 'abc' * 5")
                    1 0 LOAD_CONST 0 ('abcabcabcabcabc')
                    2 STORE_NAME 0 (x)
                    4 LOAD_CONST 1 (None)
                    6 RETURN_VALUE
                    >>> dis.dis("x = 1 + 2 + 3 + 4")
                    1 0 LOAD_CONST 0 (10)
                    2 STORE_NAME 0 (x)
                    4 LOAD_CONST 1 (None)
                    6 RETURN_VALUE





                    share|improve this answer















                    You can check that with dis.dis. The output is:



                     2 0 LOAD_CONST 0 (1)
                    2 STORE_NAME 0 (x)

                    3 4 LOAD_CONST 1 (2)
                    6 STORE_NAME 1 (y)

                    4 8 LOAD_CONST 2 (3)
                    10 STORE_NAME 2 (z)

                    5 12 LOAD_NAME 0 (x)
                    14 LOAD_NAME 1 (y)
                    16 BINARY_ADD
                    18 LOAD_NAME 2 (z)
                    20 BINARY_ADD
                    22 LOAD_CONST 0 (1)
                    24 BINARY_ADD
                    26 LOAD_NAME 0 (x)
                    28 LOAD_NAME 1 (y)
                    30 BINARY_ADD
                    32 LOAD_NAME 2 (z)
                    34 BINARY_ADD
                    36 LOAD_CONST 1 (2)
                    38 BINARY_ADD
                    40 BINARY_ADD
                    42 STORE_NAME 3 (r)
                    44 LOAD_CONST 3 (None)
                    46 RETURN_VALUE


                    So it won't cache the result of the expression in parentheses. Though for that specific case it would be possible, in general it is not, since custom classes can define __add__ (or any other binary operation) to modify themselves. For example:



                    class Foo:
                    def __init__(self, value):
                    self.value = value

                    def __add__(self, other):
                    self.value += 1
                    return self.value + other

                    x = Foo(1)
                    y = 2
                    z = 3
                    print(x + y + z + 1) # prints 8
                    print(x + y + z + 1) # prints 9


                    If you have an expensive function of which you would like to cache the result, you can do so via functools.lru_cache for example.



                    On the other hand, the compiler will perform constant folding as can be seen from the following examples:



                    >>> import dis
                    >>> dis.dis("x = 'abc' * 5")
                    1 0 LOAD_CONST 0 ('abcabcabcabcabc')
                    2 STORE_NAME 0 (x)
                    4 LOAD_CONST 1 (None)
                    6 RETURN_VALUE
                    >>> dis.dis("x = 1 + 2 + 3 + 4")
                    1 0 LOAD_CONST 0 (10)
                    2 STORE_NAME 0 (x)
                    4 LOAD_CONST 1 (None)
                    6 RETURN_VALUE






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 8 hours ago

























                    answered 8 hours ago









                    a_guesta_guest

                    9,2813 gold badges21 silver badges50 bronze badges




                    9,2813 gold badges21 silver badges50 bronze badges


























                        3
















                        No it will not. You can do this to see the compiled code:



                        from dis import dis
                        dis("r=(x+y+z+1) + (x+y+z+2)")


                        Output:



                         0 LOAD_NAME 0 (x)
                        2 LOAD_NAME 1 (y)
                        4 BINARY_ADD
                        6 LOAD_NAME 2 (z)
                        8 BINARY_ADD
                        10 LOAD_CONST 0 (1)
                        12 BINARY_ADD
                        14 LOAD_NAME 0 (x)
                        16 LOAD_NAME 1 (y)
                        18 BINARY_ADD
                        20 LOAD_NAME 2 (z)
                        22 BINARY_ADD
                        24 LOAD_CONST 1 (2)
                        26 BINARY_ADD
                        28 BINARY_ADD
                        30 STORE_NAME 3 (r)
                        32 LOAD_CONST 2 (None)
                        34 RETURN_VALUE


                        This is partially because Python is dynamically-typed. So the types of variables are not easily known at compile time. And the compiler has no way to know whether the + operator, which can be overloaded by user classes, could have any side effect at all. Consider the following simple example:



                        class A:
                        def __init__(self, v):
                        self.value = v

                        def __add__(self, b):
                        print(b)
                        return self.value + b

                        x = A(3)
                        y = 4
                        r = (x + y + 1) + (x + y + 2)


                        For simple expressions, you can just save the intermediate results to a new variable:



                        z = x + y + 1
                        r = z + (z + 1)


                        For functions calls, functools.lru_cache is another option, as already indicated by other answers.






                        share|improve this answer































                          3
















                          No it will not. You can do this to see the compiled code:



                          from dis import dis
                          dis("r=(x+y+z+1) + (x+y+z+2)")


                          Output:



                           0 LOAD_NAME 0 (x)
                          2 LOAD_NAME 1 (y)
                          4 BINARY_ADD
                          6 LOAD_NAME 2 (z)
                          8 BINARY_ADD
                          10 LOAD_CONST 0 (1)
                          12 BINARY_ADD
                          14 LOAD_NAME 0 (x)
                          16 LOAD_NAME 1 (y)
                          18 BINARY_ADD
                          20 LOAD_NAME 2 (z)
                          22 BINARY_ADD
                          24 LOAD_CONST 1 (2)
                          26 BINARY_ADD
                          28 BINARY_ADD
                          30 STORE_NAME 3 (r)
                          32 LOAD_CONST 2 (None)
                          34 RETURN_VALUE


                          This is partially because Python is dynamically-typed. So the types of variables are not easily known at compile time. And the compiler has no way to know whether the + operator, which can be overloaded by user classes, could have any side effect at all. Consider the following simple example:



                          class A:
                          def __init__(self, v):
                          self.value = v

                          def __add__(self, b):
                          print(b)
                          return self.value + b

                          x = A(3)
                          y = 4
                          r = (x + y + 1) + (x + y + 2)


                          For simple expressions, you can just save the intermediate results to a new variable:



                          z = x + y + 1
                          r = z + (z + 1)


                          For functions calls, functools.lru_cache is another option, as already indicated by other answers.






                          share|improve this answer





























                            3














                            3










                            3









                            No it will not. You can do this to see the compiled code:



                            from dis import dis
                            dis("r=(x+y+z+1) + (x+y+z+2)")


                            Output:



                             0 LOAD_NAME 0 (x)
                            2 LOAD_NAME 1 (y)
                            4 BINARY_ADD
                            6 LOAD_NAME 2 (z)
                            8 BINARY_ADD
                            10 LOAD_CONST 0 (1)
                            12 BINARY_ADD
                            14 LOAD_NAME 0 (x)
                            16 LOAD_NAME 1 (y)
                            18 BINARY_ADD
                            20 LOAD_NAME 2 (z)
                            22 BINARY_ADD
                            24 LOAD_CONST 1 (2)
                            26 BINARY_ADD
                            28 BINARY_ADD
                            30 STORE_NAME 3 (r)
                            32 LOAD_CONST 2 (None)
                            34 RETURN_VALUE


                            This is partially because Python is dynamically-typed. So the types of variables are not easily known at compile time. And the compiler has no way to know whether the + operator, which can be overloaded by user classes, could have any side effect at all. Consider the following simple example:



                            class A:
                            def __init__(self, v):
                            self.value = v

                            def __add__(self, b):
                            print(b)
                            return self.value + b

                            x = A(3)
                            y = 4
                            r = (x + y + 1) + (x + y + 2)


                            For simple expressions, you can just save the intermediate results to a new variable:



                            z = x + y + 1
                            r = z + (z + 1)


                            For functions calls, functools.lru_cache is another option, as already indicated by other answers.






                            share|improve this answer















                            No it will not. You can do this to see the compiled code:



                            from dis import dis
                            dis("r=(x+y+z+1) + (x+y+z+2)")


                            Output:



                             0 LOAD_NAME 0 (x)
                            2 LOAD_NAME 1 (y)
                            4 BINARY_ADD
                            6 LOAD_NAME 2 (z)
                            8 BINARY_ADD
                            10 LOAD_CONST 0 (1)
                            12 BINARY_ADD
                            14 LOAD_NAME 0 (x)
                            16 LOAD_NAME 1 (y)
                            18 BINARY_ADD
                            20 LOAD_NAME 2 (z)
                            22 BINARY_ADD
                            24 LOAD_CONST 1 (2)
                            26 BINARY_ADD
                            28 BINARY_ADD
                            30 STORE_NAME 3 (r)
                            32 LOAD_CONST 2 (None)
                            34 RETURN_VALUE


                            This is partially because Python is dynamically-typed. So the types of variables are not easily known at compile time. And the compiler has no way to know whether the + operator, which can be overloaded by user classes, could have any side effect at all. Consider the following simple example:



                            class A:
                            def __init__(self, v):
                            self.value = v

                            def __add__(self, b):
                            print(b)
                            return self.value + b

                            x = A(3)
                            y = 4
                            r = (x + y + 1) + (x + y + 2)


                            For simple expressions, you can just save the intermediate results to a new variable:



                            z = x + y + 1
                            r = z + (z + 1)


                            For functions calls, functools.lru_cache is another option, as already indicated by other answers.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 8 hours ago

























                            answered 8 hours ago









                            GZ0GZ0

                            2,4313 silver badges14 bronze badges




                            2,4313 silver badges14 bronze badges
























                                0
















                                No, python doesn't do that by default since it would use up too much memory, if you need python to preserve the result of a certain calculation for you, you need to implicitly tell python to do that, one way to do this would be by defining a function and useing functools.lru_cache docs:



                                from functools import lru_cache

                                @lru_cache(maxsize=32)
                                def add3(x,y,z):
                                return x + y + z

                                x=1
                                y=2
                                z=3
                                r = (add3(x,y,z)+1) + (add3(x,y,z)+2)





                                share|improve this answer





























                                  0
















                                  No, python doesn't do that by default since it would use up too much memory, if you need python to preserve the result of a certain calculation for you, you need to implicitly tell python to do that, one way to do this would be by defining a function and useing functools.lru_cache docs:



                                  from functools import lru_cache

                                  @lru_cache(maxsize=32)
                                  def add3(x,y,z):
                                  return x + y + z

                                  x=1
                                  y=2
                                  z=3
                                  r = (add3(x,y,z)+1) + (add3(x,y,z)+2)





                                  share|improve this answer



























                                    0














                                    0










                                    0









                                    No, python doesn't do that by default since it would use up too much memory, if you need python to preserve the result of a certain calculation for you, you need to implicitly tell python to do that, one way to do this would be by defining a function and useing functools.lru_cache docs:



                                    from functools import lru_cache

                                    @lru_cache(maxsize=32)
                                    def add3(x,y,z):
                                    return x + y + z

                                    x=1
                                    y=2
                                    z=3
                                    r = (add3(x,y,z)+1) + (add3(x,y,z)+2)





                                    share|improve this answer













                                    No, python doesn't do that by default since it would use up too much memory, if you need python to preserve the result of a certain calculation for you, you need to implicitly tell python to do that, one way to do this would be by defining a function and useing functools.lru_cache docs:



                                    from functools import lru_cache

                                    @lru_cache(maxsize=32)
                                    def add3(x,y,z):
                                    return x + y + z

                                    x=1
                                    y=2
                                    z=3
                                    r = (add3(x,y,z)+1) + (add3(x,y,z)+2)






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered 8 hours ago









                                    yukashima huksayyukashima huksay

                                    1,4112 gold badges15 silver badges38 bronze badges




                                    1,4112 gold badges15 silver badges38 bronze badges































                                        draft saved

                                        draft discarded















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f58146860%2fdoes-python-reuse-repeated-calculation-results%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                        Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                        François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480