473,385 Members | 1,312 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Is except: ... pass bad style?

I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass
Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style? I know there are other ways of doing it, but
of all the other "obvious" ones, this appears the most straight
forward.

Should I ignore pylint or is there a more Pythonic way to do this?
Jul 18 '05 #1
18 3215
marduk <ma****@python.net> writes:
I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass
Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style? I know there are other ways of doing it, but
of all the other "obvious" ones, this appears the most straight
forward.
Sounds like a dubious warning to me.
Should I ignore pylint or is there a more Pythonic way to do this?


Well,

try:
meth = myobj.method
except AttributeError:
pass
else:
meth()

is possibly better (your version might hide bugs in the method). It's
a pain to do this all the time, though.

Come to think of it

getattr(myobj, "method", lambda :None)()

also acheives the same thing. Bit inscrutable, though.

Cheers,
mwh

--
<thirmite> what's a web widget??
<glyph> thirmite: internet on a stick, on fire
<Acapnotic> with web sauce! -- from Twisted.Quotes
Jul 18 '05 #2
marduk <ma****@python.net> wrote:
I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass
Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style? I know there are other ways of doing it, but
of all the other "obvious" ones, this appears the most straight
forward.

Should I ignore pylint or is there a more Pythonic way to do this?


I would prefer:

try: themethod = myobj.method
except AttributeError: pass
else: themethod()

but this, too, has an empty except body, which IS pretty normal...
Alex
Jul 18 '05 #3
In article <pa****************************@python.net>,
marduk <ma****@python.net> wrote:

I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass

Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style? I know there are other ways of doing it, but
of all the other "obvious" ones, this appears the most straight
forward.

Should I ignore pylint or is there a more Pythonic way to do this?


Neither. It's a perfectly good Pythonic idiom, but it's also likely to
be programmer error (mocking up the try/except structure and forgetting
to fill in the blanks later). So you should ignore pylint when it's
code you're familiar with (and have already double-checked your
intentions), but you should pay attention to pylint when you're writing
new code and checking it.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"A foolish consistency is the hobgoblin of little minds, adored by little
statesmen and philosophers and divines." --Ralph Waldo Emerson
Jul 18 '05 #4
marduk <ma****@python.net> writes:
I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass
Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style? I know there are other ways of doing it, but
of all the other "obvious" ones, this appears the most straight
forward.

Should I ignore pylint or is there a more Pythonic way to do this?


It's better to write it this way, imo:

try:
mth = myobje.method
except AttributeError:
pass
else:
mth()

Otherwise you cannot determine whether myobj doesn't have this method,
or the method call is raising an exception.

Thomas
Jul 18 '05 #5
marduk wrote:
I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass
Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style? I know there are other ways of doing it, but
of all the other "obvious" ones, this appears the most straight
forward.

Should I ignore pylint or is there a more Pythonic way to do this?


If the class of myobj is under your control you could do

class MyObj:
def method(self):
pass

and then later just call

myobj.method()

Result: cleaner client code :-)

Peter


Jul 18 '05 #6

Based on all the responses received thus far, I thought of a way of
doing it without an exception:

myobj.__dict__.get('method', lambda : None)()

Which is okay if you don't care about the return value of the
method (in my examples I'm assuming .method() just does something
(and returns None). But it's a lot uglier I think than the try/except
block.


----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 18 '05 #7
marduk <ma****@python.net> writes:
Based on all the responses received thus far, I thought of a way of
doing it without an exception:

myobj.__dict__.get('method', lambda : None)()


Uh, I'd say that's pretty unlikely to work. What's wrong with
getattr()?

Cheers,
mwh

--
<dash> wow. this code does something highly entertaining, but
nowhere near correct -- from Twisted.Quotes
Jul 18 '05 #8
I think that the getattr option would be your best/cleanest option.
For best results, combine with the Null object pattern.
http://aspn.activestate.com/ASPN/Coo...n/Recipe/68205

getattr(myobj, 'method', Null)()

Clean, concise, and clear. Just like most of the rest of Python. ;-)

Chris
On Thu, 09 Sep 2004 12:56:55 -0500, marduk <ma****@python.net> wrote:

Based on all the responses received thus far, I thought of a way of
doing it without an exception:

myobj.__dict__.get('method', lambda : None)()

Which is okay if you don't care about the return value of the
method (in my examples I'm assuming .method() just does something
(and returns None). But it's a lot uglier I think than the try/except
block.

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
--
http://mail.python.org/mailman/listinfo/python-list


--
Still searching for an even prime > 2!
Jul 18 '05 #9
marduk wrote:
try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass
Occasionally I use pylint, which is a good tool, but in the above
snippet pylint will complain that 'Except doesn't do anything'. True,
but is that bad style?


I personally don't like this, not because of pylint but because
it feels like using the wrong solution for the problem.
You could create a base class that has a method that
does nothing and have all your objects inherit from that.

This solution does properly communicate
that the method is optional. Not to mention that you need
to repeat the whole thing if used again in a different
circumstance. Plus something could go wrong inside
existing methods and you'd never know about it.

Why risk all that?

Istvan.
Jul 18 '05 #10
In article <m3************@pc150.maths.bris.ac.uk>,
Michael Hudson <mw*@python.net> wrote:
....
Well,

try:
meth = myobj.method
except AttributeError:
pass
else:
meth()

is possibly better (your version might hide bugs in the method). It's
a pain to do this all the time, though.

Come to think of it

getattr(myobj, "method", lambda :None)()

also acheives the same thing. Bit inscrutable, though.


Along the same lines,

if hasattr(myobj, 'method'):
myobj.method()

That's not uncommon usage, and has the advantage
of more directly and economically saying what the
try/except block is trying to say.

Donn Cave, do**@u.washington.edu
Jul 18 '05 #11
Michael Hudson <mw*@python.net> writes:
marduk <ma****@python.net> writes:
I commonly use code like this

try:
# call optional method
myobj.method()
except AttributeError:
# no biggie
pass


try:
meth = myobj.method
except AttributeError:
pass
else:
meth()


I'm confused - why not

meth = getattr(myobj, method)
if meth:
meth()

--
Brandon Craig Rhodes br*****@rhodesmill.org http://rhodesmill.org/brandon
Jul 18 '05 #12
I carelessly wrote:
meth = getattr(myobj, method)
if meth:
meth()


but in fact intended the first line to be

meth = getattr(myobj, method, None)

Sorry for any confusion. :-)

--
Brandon Craig Rhodes br*****@rhodesmill.org http://rhodesmill.org/brandon
Jul 18 '05 #13
Brandon Craig Rhodes <br*****@ten22.rhodesmill.org> writes:
...but in fact intended the first line to be
meth = getattr(myobj, method, None)


.... where `method' holds the method name, of course. <sigh>

--
Brandon Craig Rhodes br*****@rhodesmill.org http://rhodesmill.org/brandon
Jul 18 '05 #14
JCM
Peter Otten <__*******@web.de> wrote:
....
If the class of myobj is under your control you could do class MyObj:
def method(self):
pass and then later just call myobj.method()


Yes. This also avoids running into trouble by catching an exception
you didn't mean to ignore.
Jul 18 '05 #15
marduk <ma****@python.net> wrote:
Based on all the responses received thus far, I thought of a way of
doing it without an exception:

myobj.__dict__.get('method', lambda : None)()


Have you TRIED this? most likely, myobj.method is NOT reaching into
myobj.__dict__, but rather into type(myobj). getattr is WAY superior!
Alex
Jul 18 '05 #16
On Thu, 09 Sep 2004 15:29:08 -0400, Istvan Albert wrote:
I personally don't like this, not because of pylint but because
it feels like using the wrong solution for the problem.
You could create a base class that has a method that
does nothing and have all your objects inherit from that.

This solution does properly communicate
that the method is optional. Not to mention that you need
to repeat the whole thing if used again in a different
circumstance. Plus something could go wrong inside
existing methods and you'd never know about it.

Why risk all that?


This is probably overkill for my current circumstance, but I may consider
it in the future. Besides, the class in question is third-party and I'm
merely trying to call method if it exists (version n) and do nothing if it
doesn't exist (version n-1). Although I could subclass the third-party
class and override method()... but as I said, overkill for me right now as
I'm only using the object/method once.

I really liked the getattr suggestion. Thanks to all who responded.

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 18 '05 #17
Am Donnerstag, 9. September 2004 19:56 schrieb marduk:
myobj.__dict__.get('method', lambda : None)()


This won't work when inheritance is in play. See for yourself:
class x(object): .... def method(self):
.... return "I was called!"
.... class y(x): .... pass
.... a = y()
a.method() 'I was called!' a.__dict__.get("method",lambda: None)()
a.__dict__.get("method")
So, use getattr, which properly walks the inheritance tree:
getattr(a,"method",lambda: None)()

'I was called!'

Heiko.
Jul 18 '05 #18
Michael Hudson wrote:
Come to think of it

getattr(myobj, "method", lambda :None)()

also acheives the same thing. Bit inscrutable, though.


Who needs a lambda?

getattr(myobj, "method", Exception)()

Even works for multiple arguments. Now if only
Exception took kwargs...

Still inscrutable, or at least distracting.

(In other words, don't use this.)

Andrew
da***@dalkescientific.com
Jul 18 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
3
by: George Young | last post by:
I have a bunch of blanket "except:" clauses like: class DatabaseError(StandardError): pass class OperationalError(StandardError): pass try: stuff except _pg.error, msg: raise...
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
1
by: pekka niiranen | last post by:
Hi there, I have defined function that calls another functions like this (modified for this mail): def main_function(): if not function1(): m = "main_function: function1 failed"...
4
by: John Salerno | last post by:
My code is below. The main focus would be on the OnStart method. I want to make sure that a positive integer is entered in the input box. At first I tried an if/else clause, then switched to...
35
by: Arnaud Delobelle | last post by:
Hi all, Imagine I have three functions a(x), b(x), c(x) that each return something or raise an exception. Imagine I want to define a function that returns a(x) if possible, otherwise b(x),...
5
by: Nebur | last post by:
I'm using the contract.py library, running Python 2.4.4. Now I'm confronted with the following exception backtrace: (...) File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in...
5
by: Fabio Z Tessitore | last post by:
Hi all, reading Dive Into Python, on Chapter 6 (exception), I've found: "This code comes from the getpass module, a wrapper module for getting a password from the user" try: import...
9
by: ssecorp | last post by:
or why does this take so god damn long time? and if I run into an IndexError it break out of the inner loop right? so having range up to 10000000 or 1000 wouldn't matter if biggest working x is...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.