Are nested python try-except blocks bad code or code smell?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I have a situation where, I get an object, fillable_object which I need to fill out and I have another object, filler_object, that I use to fill up the first object. The filler_object however, can be of different types that don't have the same attributes. In which case I want the fields related to that in the fillable_object to get the value null.



What I thought of was to group for each class that fillable_object can be, in a try except block. Since the attribute sets of the different classes are mutually exclusive it will either get all of them or non, then try for the next type etc. Currently there aren't too many classes that fillable_object can have, but I can see it as being annoying to maintain later if the number increases.



def fill_with(fillable, filler):
try:
fillable.attr1 = filler.attr1
except AttrError:
try:
fillable.attr2 = filler.attr2
fillable.attr3 = filler.attr3
except AttrError:
try:
#Continue for each class filler can be.
except AttrError:
return fillable









share|improve this question























  • To avoid nesting you can place a return at the end of each try block and a "pass" in the except. So the try blocks can be placed one after another.

    – Michael Butscher
    Nov 23 '18 at 14:44













  • Yea but if I do that it would be redundant. If the filler object is of one type it can't be of any of the others so I would do x assignments redundant and throw class_count of exceptions. It might not be much of a resource waste but still

    – BigBadCoder
    Nov 23 '18 at 15:28






  • 1





    looks like XY problem...

    – hkBst
    Nov 23 '18 at 18:03











  • @hkBst Could you please elaborate?

    – BigBadCoder
    Nov 23 '18 at 20:40






  • 1





    To test if a particular attribute is present, there is hasattr(). To test for the type/class of an object there are type() and isinstance().

    – Michael Butscher
    Nov 23 '18 at 23:41


















1















I have a situation where, I get an object, fillable_object which I need to fill out and I have another object, filler_object, that I use to fill up the first object. The filler_object however, can be of different types that don't have the same attributes. In which case I want the fields related to that in the fillable_object to get the value null.



What I thought of was to group for each class that fillable_object can be, in a try except block. Since the attribute sets of the different classes are mutually exclusive it will either get all of them or non, then try for the next type etc. Currently there aren't too many classes that fillable_object can have, but I can see it as being annoying to maintain later if the number increases.



def fill_with(fillable, filler):
try:
fillable.attr1 = filler.attr1
except AttrError:
try:
fillable.attr2 = filler.attr2
fillable.attr3 = filler.attr3
except AttrError:
try:
#Continue for each class filler can be.
except AttrError:
return fillable









share|improve this question























  • To avoid nesting you can place a return at the end of each try block and a "pass" in the except. So the try blocks can be placed one after another.

    – Michael Butscher
    Nov 23 '18 at 14:44













  • Yea but if I do that it would be redundant. If the filler object is of one type it can't be of any of the others so I would do x assignments redundant and throw class_count of exceptions. It might not be much of a resource waste but still

    – BigBadCoder
    Nov 23 '18 at 15:28






  • 1





    looks like XY problem...

    – hkBst
    Nov 23 '18 at 18:03











  • @hkBst Could you please elaborate?

    – BigBadCoder
    Nov 23 '18 at 20:40






  • 1





    To test if a particular attribute is present, there is hasattr(). To test for the type/class of an object there are type() and isinstance().

    – Michael Butscher
    Nov 23 '18 at 23:41














1












1








1


0






I have a situation where, I get an object, fillable_object which I need to fill out and I have another object, filler_object, that I use to fill up the first object. The filler_object however, can be of different types that don't have the same attributes. In which case I want the fields related to that in the fillable_object to get the value null.



What I thought of was to group for each class that fillable_object can be, in a try except block. Since the attribute sets of the different classes are mutually exclusive it will either get all of them or non, then try for the next type etc. Currently there aren't too many classes that fillable_object can have, but I can see it as being annoying to maintain later if the number increases.



def fill_with(fillable, filler):
try:
fillable.attr1 = filler.attr1
except AttrError:
try:
fillable.attr2 = filler.attr2
fillable.attr3 = filler.attr3
except AttrError:
try:
#Continue for each class filler can be.
except AttrError:
return fillable









share|improve this question














I have a situation where, I get an object, fillable_object which I need to fill out and I have another object, filler_object, that I use to fill up the first object. The filler_object however, can be of different types that don't have the same attributes. In which case I want the fields related to that in the fillable_object to get the value null.



What I thought of was to group for each class that fillable_object can be, in a try except block. Since the attribute sets of the different classes are mutually exclusive it will either get all of them or non, then try for the next type etc. Currently there aren't too many classes that fillable_object can have, but I can see it as being annoying to maintain later if the number increases.



def fill_with(fillable, filler):
try:
fillable.attr1 = filler.attr1
except AttrError:
try:
fillable.attr2 = filler.attr2
fillable.attr3 = filler.attr3
except AttrError:
try:
#Continue for each class filler can be.
except AttrError:
return fillable






python functional-programming






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 14:30









BigBadCoderBigBadCoder

5121420




5121420













  • To avoid nesting you can place a return at the end of each try block and a "pass" in the except. So the try blocks can be placed one after another.

    – Michael Butscher
    Nov 23 '18 at 14:44













  • Yea but if I do that it would be redundant. If the filler object is of one type it can't be of any of the others so I would do x assignments redundant and throw class_count of exceptions. It might not be much of a resource waste but still

    – BigBadCoder
    Nov 23 '18 at 15:28






  • 1





    looks like XY problem...

    – hkBst
    Nov 23 '18 at 18:03











  • @hkBst Could you please elaborate?

    – BigBadCoder
    Nov 23 '18 at 20:40






  • 1





    To test if a particular attribute is present, there is hasattr(). To test for the type/class of an object there are type() and isinstance().

    – Michael Butscher
    Nov 23 '18 at 23:41



















  • To avoid nesting you can place a return at the end of each try block and a "pass" in the except. So the try blocks can be placed one after another.

    – Michael Butscher
    Nov 23 '18 at 14:44













  • Yea but if I do that it would be redundant. If the filler object is of one type it can't be of any of the others so I would do x assignments redundant and throw class_count of exceptions. It might not be much of a resource waste but still

    – BigBadCoder
    Nov 23 '18 at 15:28






  • 1





    looks like XY problem...

    – hkBst
    Nov 23 '18 at 18:03











  • @hkBst Could you please elaborate?

    – BigBadCoder
    Nov 23 '18 at 20:40






  • 1





    To test if a particular attribute is present, there is hasattr(). To test for the type/class of an object there are type() and isinstance().

    – Michael Butscher
    Nov 23 '18 at 23:41

















To avoid nesting you can place a return at the end of each try block and a "pass" in the except. So the try blocks can be placed one after another.

– Michael Butscher
Nov 23 '18 at 14:44







To avoid nesting you can place a return at the end of each try block and a "pass" in the except. So the try blocks can be placed one after another.

– Michael Butscher
Nov 23 '18 at 14:44















Yea but if I do that it would be redundant. If the filler object is of one type it can't be of any of the others so I would do x assignments redundant and throw class_count of exceptions. It might not be much of a resource waste but still

– BigBadCoder
Nov 23 '18 at 15:28





Yea but if I do that it would be redundant. If the filler object is of one type it can't be of any of the others so I would do x assignments redundant and throw class_count of exceptions. It might not be much of a resource waste but still

– BigBadCoder
Nov 23 '18 at 15:28




1




1





looks like XY problem...

– hkBst
Nov 23 '18 at 18:03





looks like XY problem...

– hkBst
Nov 23 '18 at 18:03













@hkBst Could you please elaborate?

– BigBadCoder
Nov 23 '18 at 20:40





@hkBst Could you please elaborate?

– BigBadCoder
Nov 23 '18 at 20:40




1




1





To test if a particular attribute is present, there is hasattr(). To test for the type/class of an object there are type() and isinstance().

– Michael Butscher
Nov 23 '18 at 23:41





To test if a particular attribute is present, there is hasattr(). To test for the type/class of an object there are type() and isinstance().

– Michael Butscher
Nov 23 '18 at 23:41












1 Answer
1






active

oldest

votes


















0














Yes this is definitely a code smell, and you found why: what happens when you add new filler objects? You have to rewrite your function. This is a violation of the Open-closed principle.




software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification




Concretely, you can use some workarounds, but you are in a typical "big switch" that could/should be replaced by a wise usage of polymorphism.



In your example, it's filler that triggers the exceptions: if filler.attr1 does not exist, then try the next attribute(s), and so on. The filler object has the knowledge, thus you should put the fill_with method in filler.



class FillerA():
...

def fill(self, fillable):
fillable.attr1 = self.attr1

class FillerB():
...

def fill(self, fillable):
fillable.attr2 = self.attr2
fillable.attr3 = self.attr3

...


Now your function is just:



def fill_with(fillable, filler):
filler.fill(fillable)


This function is closed for modification, but you can extend it by adding a new filler type (with the method fill). Bonus: filler does not need to expose his attributes anymore.






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%2f53448546%2fare-nested-python-try-except-blocks-bad-code-or-code-smell%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Yes this is definitely a code smell, and you found why: what happens when you add new filler objects? You have to rewrite your function. This is a violation of the Open-closed principle.




    software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification




    Concretely, you can use some workarounds, but you are in a typical "big switch" that could/should be replaced by a wise usage of polymorphism.



    In your example, it's filler that triggers the exceptions: if filler.attr1 does not exist, then try the next attribute(s), and so on. The filler object has the knowledge, thus you should put the fill_with method in filler.



    class FillerA():
    ...

    def fill(self, fillable):
    fillable.attr1 = self.attr1

    class FillerB():
    ...

    def fill(self, fillable):
    fillable.attr2 = self.attr2
    fillable.attr3 = self.attr3

    ...


    Now your function is just:



    def fill_with(fillable, filler):
    filler.fill(fillable)


    This function is closed for modification, but you can extend it by adding a new filler type (with the method fill). Bonus: filler does not need to expose his attributes anymore.






    share|improve this answer




























      0














      Yes this is definitely a code smell, and you found why: what happens when you add new filler objects? You have to rewrite your function. This is a violation of the Open-closed principle.




      software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification




      Concretely, you can use some workarounds, but you are in a typical "big switch" that could/should be replaced by a wise usage of polymorphism.



      In your example, it's filler that triggers the exceptions: if filler.attr1 does not exist, then try the next attribute(s), and so on. The filler object has the knowledge, thus you should put the fill_with method in filler.



      class FillerA():
      ...

      def fill(self, fillable):
      fillable.attr1 = self.attr1

      class FillerB():
      ...

      def fill(self, fillable):
      fillable.attr2 = self.attr2
      fillable.attr3 = self.attr3

      ...


      Now your function is just:



      def fill_with(fillable, filler):
      filler.fill(fillable)


      This function is closed for modification, but you can extend it by adding a new filler type (with the method fill). Bonus: filler does not need to expose his attributes anymore.






      share|improve this answer


























        0












        0








        0







        Yes this is definitely a code smell, and you found why: what happens when you add new filler objects? You have to rewrite your function. This is a violation of the Open-closed principle.




        software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification




        Concretely, you can use some workarounds, but you are in a typical "big switch" that could/should be replaced by a wise usage of polymorphism.



        In your example, it's filler that triggers the exceptions: if filler.attr1 does not exist, then try the next attribute(s), and so on. The filler object has the knowledge, thus you should put the fill_with method in filler.



        class FillerA():
        ...

        def fill(self, fillable):
        fillable.attr1 = self.attr1

        class FillerB():
        ...

        def fill(self, fillable):
        fillable.attr2 = self.attr2
        fillable.attr3 = self.attr3

        ...


        Now your function is just:



        def fill_with(fillable, filler):
        filler.fill(fillable)


        This function is closed for modification, but you can extend it by adding a new filler type (with the method fill). Bonus: filler does not need to expose his attributes anymore.






        share|improve this answer













        Yes this is definitely a code smell, and you found why: what happens when you add new filler objects? You have to rewrite your function. This is a violation of the Open-closed principle.




        software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification




        Concretely, you can use some workarounds, but you are in a typical "big switch" that could/should be replaced by a wise usage of polymorphism.



        In your example, it's filler that triggers the exceptions: if filler.attr1 does not exist, then try the next attribute(s), and so on. The filler object has the knowledge, thus you should put the fill_with method in filler.



        class FillerA():
        ...

        def fill(self, fillable):
        fillable.attr1 = self.attr1

        class FillerB():
        ...

        def fill(self, fillable):
        fillable.attr2 = self.attr2
        fillable.attr3 = self.attr3

        ...


        Now your function is just:



        def fill_with(fillable, filler):
        filler.fill(fillable)


        This function is closed for modification, but you can extend it by adding a new filler type (with the method fill). Bonus: filler does not need to expose his attributes anymore.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Feb 13 at 16:32









        jferardjferard

        2,1561312




        2,1561312
































            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%2f53448546%2fare-nested-python-try-except-blocks-bad-code-or-code-smell%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

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy