Python try: ing not to repeat code. try: except and else
I have this:
try:
if session.var:
otherVar = session.var
else:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
except AttributeError:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
...do stuff with otherVar
The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.
How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?
python python-2.7 web2py try-except
add a comment |
I have this:
try:
if session.var:
otherVar = session.var
else:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
except AttributeError:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
...do stuff with otherVar
The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.
How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?
python python-2.7 web2py try-except
add a comment |
I have this:
try:
if session.var:
otherVar = session.var
else:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
except AttributeError:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
...do stuff with otherVar
The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.
How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?
python python-2.7 web2py try-except
I have this:
try:
if session.var:
otherVar = session.var
else:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
except AttributeError:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
...do stuff with otherVar
The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.
How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?
python python-2.7 web2py try-except
python python-2.7 web2py try-except
edited Nov 17 '18 at 0:20
Blckknght
62.4k556100
62.4k556100
asked Nov 17 '18 at 0:00
EddieEddie
174
174
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Assuming this is a web2py session
object, note that it is an instance of gluon.Storage
, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None
rather than raising an exception. So, you can simply do something like:
otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank
Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None
, you cannot use hasattr(session, 'var')
, as that will return True
even if there is no 'var'
key. Instead, you can check session.has_key('var')
, which will return False
if there is no 'var'
key.
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
add a comment |
You can avoid using session.var
if it doesn't exist by checking for it first, using hasattr
. This avoids the need for the try
/except
block all together.
if hasattr(session, 'var') and session.var is not None:
...
else:
...
An alternative might be to have the else
in your original code just raise
an exception to get to the except
block, but it's sort of ugly:
try:
if session.var:
...
else:
raise AttributeError
except AttributeError:
...
In this situation, I think the "Look Before you Leap" style of programming (using hasattr
) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.
If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var
function, it could return
from the successful case (inside the try
and if
blocks), and the two error cases could be resolved later:
def get_session_var(session):
try:
if session.var:
return session.var
except AttributeError:
pass
util = db.utility[1]
session.var = util.freshOutTheBank
return session.var
Orif getattr(session, 'var', None) is not None
, to fuse the existence/None checks.
– user2357112
Nov 17 '18 at 0:23
As noted here,hasattr(session, 'var')
is not necessary with the web2pysession
object, as it will simply returnNone
for a non-existent key/property rather than raising an exception.
– Anthony
Nov 17 '18 at 14:24
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
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%2f53346918%2fpython-try-ing-not-to-repeat-code-try-except-and-else%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
Assuming this is a web2py session
object, note that it is an instance of gluon.Storage
, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None
rather than raising an exception. So, you can simply do something like:
otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank
Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None
, you cannot use hasattr(session, 'var')
, as that will return True
even if there is no 'var'
key. Instead, you can check session.has_key('var')
, which will return False
if there is no 'var'
key.
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
add a comment |
Assuming this is a web2py session
object, note that it is an instance of gluon.Storage
, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None
rather than raising an exception. So, you can simply do something like:
otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank
Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None
, you cannot use hasattr(session, 'var')
, as that will return True
even if there is no 'var'
key. Instead, you can check session.has_key('var')
, which will return False
if there is no 'var'
key.
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
add a comment |
Assuming this is a web2py session
object, note that it is an instance of gluon.Storage
, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None
rather than raising an exception. So, you can simply do something like:
otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank
Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None
, you cannot use hasattr(session, 'var')
, as that will return True
even if there is no 'var'
key. Instead, you can check session.has_key('var')
, which will return False
if there is no 'var'
key.
Assuming this is a web2py session
object, note that it is an instance of gluon.Storage
, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None
rather than raising an exception. So, you can simply do something like:
otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank
Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None
, you cannot use hasattr(session, 'var')
, as that will return True
even if there is no 'var'
key. Instead, you can check session.has_key('var')
, which will return False
if there is no 'var'
key.
answered Nov 17 '18 at 14:22
AnthonyAnthony
23.9k32051
23.9k32051
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
add a comment |
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.
– Eddie
Nov 18 '18 at 11:54
add a comment |
You can avoid using session.var
if it doesn't exist by checking for it first, using hasattr
. This avoids the need for the try
/except
block all together.
if hasattr(session, 'var') and session.var is not None:
...
else:
...
An alternative might be to have the else
in your original code just raise
an exception to get to the except
block, but it's sort of ugly:
try:
if session.var:
...
else:
raise AttributeError
except AttributeError:
...
In this situation, I think the "Look Before you Leap" style of programming (using hasattr
) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.
If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var
function, it could return
from the successful case (inside the try
and if
blocks), and the two error cases could be resolved later:
def get_session_var(session):
try:
if session.var:
return session.var
except AttributeError:
pass
util = db.utility[1]
session.var = util.freshOutTheBank
return session.var
Orif getattr(session, 'var', None) is not None
, to fuse the existence/None checks.
– user2357112
Nov 17 '18 at 0:23
As noted here,hasattr(session, 'var')
is not necessary with the web2pysession
object, as it will simply returnNone
for a non-existent key/property rather than raising an exception.
– Anthony
Nov 17 '18 at 14:24
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
add a comment |
You can avoid using session.var
if it doesn't exist by checking for it first, using hasattr
. This avoids the need for the try
/except
block all together.
if hasattr(session, 'var') and session.var is not None:
...
else:
...
An alternative might be to have the else
in your original code just raise
an exception to get to the except
block, but it's sort of ugly:
try:
if session.var:
...
else:
raise AttributeError
except AttributeError:
...
In this situation, I think the "Look Before you Leap" style of programming (using hasattr
) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.
If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var
function, it could return
from the successful case (inside the try
and if
blocks), and the two error cases could be resolved later:
def get_session_var(session):
try:
if session.var:
return session.var
except AttributeError:
pass
util = db.utility[1]
session.var = util.freshOutTheBank
return session.var
Orif getattr(session, 'var', None) is not None
, to fuse the existence/None checks.
– user2357112
Nov 17 '18 at 0:23
As noted here,hasattr(session, 'var')
is not necessary with the web2pysession
object, as it will simply returnNone
for a non-existent key/property rather than raising an exception.
– Anthony
Nov 17 '18 at 14:24
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
add a comment |
You can avoid using session.var
if it doesn't exist by checking for it first, using hasattr
. This avoids the need for the try
/except
block all together.
if hasattr(session, 'var') and session.var is not None:
...
else:
...
An alternative might be to have the else
in your original code just raise
an exception to get to the except
block, but it's sort of ugly:
try:
if session.var:
...
else:
raise AttributeError
except AttributeError:
...
In this situation, I think the "Look Before you Leap" style of programming (using hasattr
) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.
If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var
function, it could return
from the successful case (inside the try
and if
blocks), and the two error cases could be resolved later:
def get_session_var(session):
try:
if session.var:
return session.var
except AttributeError:
pass
util = db.utility[1]
session.var = util.freshOutTheBank
return session.var
You can avoid using session.var
if it doesn't exist by checking for it first, using hasattr
. This avoids the need for the try
/except
block all together.
if hasattr(session, 'var') and session.var is not None:
...
else:
...
An alternative might be to have the else
in your original code just raise
an exception to get to the except
block, but it's sort of ugly:
try:
if session.var:
...
else:
raise AttributeError
except AttributeError:
...
In this situation, I think the "Look Before you Leap" style of programming (using hasattr
) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.
If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var
function, it could return
from the successful case (inside the try
and if
blocks), and the two error cases could be resolved later:
def get_session_var(session):
try:
if session.var:
return session.var
except AttributeError:
pass
util = db.utility[1]
session.var = util.freshOutTheBank
return session.var
answered Nov 17 '18 at 0:20
BlckknghtBlckknght
62.4k556100
62.4k556100
Orif getattr(session, 'var', None) is not None
, to fuse the existence/None checks.
– user2357112
Nov 17 '18 at 0:23
As noted here,hasattr(session, 'var')
is not necessary with the web2pysession
object, as it will simply returnNone
for a non-existent key/property rather than raising an exception.
– Anthony
Nov 17 '18 at 14:24
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
add a comment |
Orif getattr(session, 'var', None) is not None
, to fuse the existence/None checks.
– user2357112
Nov 17 '18 at 0:23
As noted here,hasattr(session, 'var')
is not necessary with the web2pysession
object, as it will simply returnNone
for a non-existent key/property rather than raising an exception.
– Anthony
Nov 17 '18 at 14:24
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
Or
if getattr(session, 'var', None) is not None
, to fuse the existence/None checks.– user2357112
Nov 17 '18 at 0:23
Or
if getattr(session, 'var', None) is not None
, to fuse the existence/None checks.– user2357112
Nov 17 '18 at 0:23
As noted here,
hasattr(session, 'var')
is not necessary with the web2py session
object, as it will simply return None
for a non-existent key/property rather than raising an exception.– Anthony
Nov 17 '18 at 14:24
As noted here,
hasattr(session, 'var')
is not necessary with the web2py session
object, as it will simply return None
for a non-existent key/property rather than raising an exception.– Anthony
Nov 17 '18 at 14:24
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
I was trying to avoid checking. Going with the Duck-Typing concept.
– Eddie
Nov 18 '18 at 11:52
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%2f53346918%2fpython-try-ing-not-to-repeat-code-try-except-and-else%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