Python Function with list as argument OR multiple values as argument












2














I want to write a python function my_sum that extends python's built-in sum in the following way:




  • If a sequence is passed to my_sum it behaves like the built-in sum.

  • If multiple values are passed to my_sum, it returns the sum of the values.


Desired output:



my_sum([1, 2, 3])  # shall return 6 (similiar to built-in sum)
my_sum(1, 2, 3) # shall return 6 as well, (sum throws TypeError)


What worked was the following.



def my_sum(*x):
try:
return sum(x) # sums multiple values
except TypeError:
return sum(*x) # sums sequence of values


Is that the pythonic way to accomplish the desired behavior? For me the code looks odd.










share|improve this question






















  • this doesn't belong here but in Code Review, I am voting to close this
    – aws_apprentice
    Nov 21 '18 at 16:28










  • What is odd about it? try:..except is fine.
    – juanpa.arrivillaga
    Nov 21 '18 at 17:19
















2














I want to write a python function my_sum that extends python's built-in sum in the following way:




  • If a sequence is passed to my_sum it behaves like the built-in sum.

  • If multiple values are passed to my_sum, it returns the sum of the values.


Desired output:



my_sum([1, 2, 3])  # shall return 6 (similiar to built-in sum)
my_sum(1, 2, 3) # shall return 6 as well, (sum throws TypeError)


What worked was the following.



def my_sum(*x):
try:
return sum(x) # sums multiple values
except TypeError:
return sum(*x) # sums sequence of values


Is that the pythonic way to accomplish the desired behavior? For me the code looks odd.










share|improve this question






















  • this doesn't belong here but in Code Review, I am voting to close this
    – aws_apprentice
    Nov 21 '18 at 16:28










  • What is odd about it? try:..except is fine.
    – juanpa.arrivillaga
    Nov 21 '18 at 17:19














2












2








2







I want to write a python function my_sum that extends python's built-in sum in the following way:




  • If a sequence is passed to my_sum it behaves like the built-in sum.

  • If multiple values are passed to my_sum, it returns the sum of the values.


Desired output:



my_sum([1, 2, 3])  # shall return 6 (similiar to built-in sum)
my_sum(1, 2, 3) # shall return 6 as well, (sum throws TypeError)


What worked was the following.



def my_sum(*x):
try:
return sum(x) # sums multiple values
except TypeError:
return sum(*x) # sums sequence of values


Is that the pythonic way to accomplish the desired behavior? For me the code looks odd.










share|improve this question













I want to write a python function my_sum that extends python's built-in sum in the following way:




  • If a sequence is passed to my_sum it behaves like the built-in sum.

  • If multiple values are passed to my_sum, it returns the sum of the values.


Desired output:



my_sum([1, 2, 3])  # shall return 6 (similiar to built-in sum)
my_sum(1, 2, 3) # shall return 6 as well, (sum throws TypeError)


What worked was the following.



def my_sum(*x):
try:
return sum(x) # sums multiple values
except TypeError:
return sum(*x) # sums sequence of values


Is that the pythonic way to accomplish the desired behavior? For me the code looks odd.







python function






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 16:27









Alex G

1476




1476












  • this doesn't belong here but in Code Review, I am voting to close this
    – aws_apprentice
    Nov 21 '18 at 16:28










  • What is odd about it? try:..except is fine.
    – juanpa.arrivillaga
    Nov 21 '18 at 17:19


















  • this doesn't belong here but in Code Review, I am voting to close this
    – aws_apprentice
    Nov 21 '18 at 16:28










  • What is odd about it? try:..except is fine.
    – juanpa.arrivillaga
    Nov 21 '18 at 17:19
















this doesn't belong here but in Code Review, I am voting to close this
– aws_apprentice
Nov 21 '18 at 16:28




this doesn't belong here but in Code Review, I am voting to close this
– aws_apprentice
Nov 21 '18 at 16:28












What is odd about it? try:..except is fine.
– juanpa.arrivillaga
Nov 21 '18 at 17:19




What is odd about it? try:..except is fine.
– juanpa.arrivillaga
Nov 21 '18 at 17:19












2 Answers
2






active

oldest

votes


















2














It is pythonic. I think at least one check is required and python has the philosophy "Ask for forgiveness not permission" (explained here) which basically means that using try-except blocks is OK for standard control flows.



If importing an established library is pythonic and something you are allowed and willing to do, you can use numpy.sum too, as follows:



import numpy as np
def my_sum(*x):
return np.sum(x)


With this definition, both



my_sum([1, 2, 3])  
my_sum(1, 2, 3)


return 6.






share|improve this answer































    0














    I think it is not an use case for exceptions, exceptions are for exceptional cases. Use another function if you convert arguments to a list and pass to the adder function.



    In addition, the validation and formatting of the input should be in the outer part of the code, not in the final function. In the best case the data should be validated before coming to this function, and you should only have the sum function to deal with the cooked data.



    It's a way to:




    • Keep things simple

    • Avoid adding conditional paths

    • Avoid defensive programming in inner code

    • And thus avoid future problems.


    I would have the following code.



    def argsToList(*x):
    return list(x)

    print sum([1,2,3,4])
    print sum(argsToList(1,2,3,4))
    # both output 10





    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/3.0/"u003ecc by-sa 3.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%2f53416484%2fpython-function-with-list-as-argument-or-multiple-values-as-argument%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      It is pythonic. I think at least one check is required and python has the philosophy "Ask for forgiveness not permission" (explained here) which basically means that using try-except blocks is OK for standard control flows.



      If importing an established library is pythonic and something you are allowed and willing to do, you can use numpy.sum too, as follows:



      import numpy as np
      def my_sum(*x):
      return np.sum(x)


      With this definition, both



      my_sum([1, 2, 3])  
      my_sum(1, 2, 3)


      return 6.






      share|improve this answer




























        2














        It is pythonic. I think at least one check is required and python has the philosophy "Ask for forgiveness not permission" (explained here) which basically means that using try-except blocks is OK for standard control flows.



        If importing an established library is pythonic and something you are allowed and willing to do, you can use numpy.sum too, as follows:



        import numpy as np
        def my_sum(*x):
        return np.sum(x)


        With this definition, both



        my_sum([1, 2, 3])  
        my_sum(1, 2, 3)


        return 6.






        share|improve this answer


























          2












          2








          2






          It is pythonic. I think at least one check is required and python has the philosophy "Ask for forgiveness not permission" (explained here) which basically means that using try-except blocks is OK for standard control flows.



          If importing an established library is pythonic and something you are allowed and willing to do, you can use numpy.sum too, as follows:



          import numpy as np
          def my_sum(*x):
          return np.sum(x)


          With this definition, both



          my_sum([1, 2, 3])  
          my_sum(1, 2, 3)


          return 6.






          share|improve this answer














          It is pythonic. I think at least one check is required and python has the philosophy "Ask for forgiveness not permission" (explained here) which basically means that using try-except blocks is OK for standard control flows.



          If importing an established library is pythonic and something you are allowed and willing to do, you can use numpy.sum too, as follows:



          import numpy as np
          def my_sum(*x):
          return np.sum(x)


          With this definition, both



          my_sum([1, 2, 3])  
          my_sum(1, 2, 3)


          return 6.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 17:26

























          answered Nov 21 '18 at 17:16









          Julian Peller

          864511




          864511

























              0














              I think it is not an use case for exceptions, exceptions are for exceptional cases. Use another function if you convert arguments to a list and pass to the adder function.



              In addition, the validation and formatting of the input should be in the outer part of the code, not in the final function. In the best case the data should be validated before coming to this function, and you should only have the sum function to deal with the cooked data.



              It's a way to:




              • Keep things simple

              • Avoid adding conditional paths

              • Avoid defensive programming in inner code

              • And thus avoid future problems.


              I would have the following code.



              def argsToList(*x):
              return list(x)

              print sum([1,2,3,4])
              print sum(argsToList(1,2,3,4))
              # both output 10





              share|improve this answer


























                0














                I think it is not an use case for exceptions, exceptions are for exceptional cases. Use another function if you convert arguments to a list and pass to the adder function.



                In addition, the validation and formatting of the input should be in the outer part of the code, not in the final function. In the best case the data should be validated before coming to this function, and you should only have the sum function to deal with the cooked data.



                It's a way to:




                • Keep things simple

                • Avoid adding conditional paths

                • Avoid defensive programming in inner code

                • And thus avoid future problems.


                I would have the following code.



                def argsToList(*x):
                return list(x)

                print sum([1,2,3,4])
                print sum(argsToList(1,2,3,4))
                # both output 10





                share|improve this answer
























                  0












                  0








                  0






                  I think it is not an use case for exceptions, exceptions are for exceptional cases. Use another function if you convert arguments to a list and pass to the adder function.



                  In addition, the validation and formatting of the input should be in the outer part of the code, not in the final function. In the best case the data should be validated before coming to this function, and you should only have the sum function to deal with the cooked data.



                  It's a way to:




                  • Keep things simple

                  • Avoid adding conditional paths

                  • Avoid defensive programming in inner code

                  • And thus avoid future problems.


                  I would have the following code.



                  def argsToList(*x):
                  return list(x)

                  print sum([1,2,3,4])
                  print sum(argsToList(1,2,3,4))
                  # both output 10





                  share|improve this answer












                  I think it is not an use case for exceptions, exceptions are for exceptional cases. Use another function if you convert arguments to a list and pass to the adder function.



                  In addition, the validation and formatting of the input should be in the outer part of the code, not in the final function. In the best case the data should be validated before coming to this function, and you should only have the sum function to deal with the cooked data.



                  It's a way to:




                  • Keep things simple

                  • Avoid adding conditional paths

                  • Avoid defensive programming in inner code

                  • And thus avoid future problems.


                  I would have the following code.



                  def argsToList(*x):
                  return list(x)

                  print sum([1,2,3,4])
                  print sum(argsToList(1,2,3,4))
                  # both output 10






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 17:56









                  David Lemon

                  959617




                  959617






























                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53416484%2fpython-function-with-list-as-argument-or-multiple-values-as-argument%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

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'