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;
}
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
add a comment |
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
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 ishasattr()
. To test for the type/class of an object there aretype()
andisinstance()
.
– Michael Butscher
Nov 23 '18 at 23:41
add a comment |
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
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
python functional-programming
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 ishasattr()
. To test for the type/class of an object there aretype()
andisinstance()
.
– Michael Butscher
Nov 23 '18 at 23:41
add a comment |
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 ishasattr()
. To test for the type/class of an object there aretype()
andisinstance()
.
– 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
add a comment |
1 Answer
1
active
oldest
votes
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.
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
answered Feb 13 at 16:32
jferardjferard
2,1561312
2,1561312
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 aretype()
andisinstance()
.– Michael Butscher
Nov 23 '18 at 23:41