473,473 Members | 2,300 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Check existence of members/methods

Hi everyone,
I'm wondering what is the easiest/cleanest way to look for existence of
available methods/members.

For example, in parsing a xml file, created objects can define a
setXmlFilename function or a xmlFilename member to get the filename they
are from.

Right now I have the following code:

try: object.setXmlFilename
except:
try: object.xmlFilename
except: pass
else: object.xmlFilename = currentFilename
else: object.setXmlFilename(currentFilename)

But it looks a bit wierd, since it's like a "if" with the false
consequence presented first. I wonder if there is, and if there should
be a better way to do it. I could also do the following:

def noraise(expressionString):
try: eval(expressionString)
except: return True
return False

if noraise("object.setXmlFilename"):
object.setXmlFilename(currentFilename)
elif noraise("object.xmlFilename"):
object.xmlFilename = currentFilename

But it puts code in strings, which I feel less natural. What do you
think about it? Have I miss a better solution or is there something for
that in the language?

Regards,
Nicolas
Jul 18 '05 #1
4 2519
Nicolas Fleury wrote:
Hi everyone,
I'm wondering what is the easiest/cleanest way to look for existence
of available methods/members.

For example, in parsing a xml file, created objects can define a
setXmlFilename function or a xmlFilename member to get the filename they
are from.

Right now I have the following code:

try: object.setXmlFilename
except:
try: object.xmlFilename
except: pass
else: object.xmlFilename = currentFilename
else: object.setXmlFilename(currentFilename)

But it looks a bit wierd, since it's like a "if" with the false
consequence presented first. I wonder if there is, and if there should
be a better way to do it. I could also do the following:

def noraise(expressionString):
try: eval(expressionString)
except: return True
return False

if noraise("object.setXmlFilename"):
object.setXmlFilename(currentFilename)
elif noraise("object.xmlFilename"):
object.xmlFilename = currentFilename


In fact, it's even more ugly:

def exists(obj, name):
try: eval("obj." + name)
except: return True
return False

if exists(object, "setXmlFilename"):
object.setXmlFilename(currentFilename)
elif exists(object, "xmlFilename"):
object.xmlFilename = currentFilename
Jul 18 '05 #2
Nicolas Fleury wrote:
But it puts code in strings, which I feel less natural. What do you
think about it? Have I miss a better solution or is there something
for
that in the language?


Try hasattr.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ There is nothing so subject to the inconstancy of fortune as war.
-- Miguel de Cervantes
Jul 18 '05 #3
Nicolas Fleury <ni******@yahoo.com_remove_the_> wrote:
...
def noraise(expressionString):
try: eval(expressionString)
except: return True
return False

if noraise("object.setXmlFilename"):
object.setXmlFilename(currentFilename)
elif noraise("object.xmlFilename"):
object.xmlFilename = currentFilename

But it puts code in strings, which I feel less natural. What do you
think about it? Have I miss a better solution or is there something for
that in the language?

try: meth = object.setXmlFilename
except AttributeError: meth = lambda x: setattr(object,'xmlFilename',x)
meth(currentFillename)

This doesn't assume that object.xmlFilename must already exist before
you can set it, which IS implied by your code here quoted -- it just
seems a slightly weird condition to me.

I personally prefer the try/except/else variant:

try: meth = object.setXmlFilename
except AttributeError: object.xmlFilename = x
else: meth(currentFillename)

it seems way simpler to me. However, if you think of objects lacking a
setter method as weird and exceptional ones, I see why this might seem
backwards. Personally, I consider setter methods the anomaly (it's
exactly to avoid them that we have property...:-) but I do understand
they're frequently used. If I often had to fight with objects full of
getThis, setThat methods I'd wrap them into a generic wrapper with a
__setattr__ and __getattr__ to be able to use attribute get and set as
common sense and decency require, e.g, something like....:

class MakeSensible:
def __init__(self, obj): self.__dict__['obj'] = obj
def __getattr__(self, name):
methname = 'get' + name[0].uppercase() + name[:1]
return getattr(self.obj,methname)()
def __setattr__(self, name, value):
methname = 'set' + name[0].uppercase() + name[:1]
return getattr(self.obj,methname)(value)

(or, you could build all the needed properties at wrapping time, but
it's unclear if that would be an advantage in performance and it would
surely take a bit more code!-). Having made the object sensible once
and for all, thanks to this wrapper, you wouldn't need to thread
carefully throughout the rest of your application...
Alex
Jul 18 '05 #4
Alex Martelli wrote:
try: meth = object.setXmlFilename
except AttributeError: meth = lambda x: setattr(object,'xmlFilename',x)
meth(currentFillename)

This doesn't assume that object.xmlFilename must already exist before
you can set it, which IS implied by your code here quoted -- it just
seems a slightly weird condition to me.
In my case, a xml parser/saving creating objects corresponding to
elements and vice-versa, forcing the existence of members before setting
them makes the code more readable (and avoid a lot of errors). I agree
it would be a weird restriction in other situations.
I personally prefer the try/except/else variant:

try: meth = object.setXmlFilename
except AttributeError: object.xmlFilename = x
else: meth(currentFillename)

it seems way simpler to me. However, if you think of objects lacking a
setter method as weird and exceptional ones, I see why this might seem
backwards. Personally, I consider setter methods the anomaly (it's
exactly to avoid them that we have property...:-) but I do understand
they're frequently used. If I often had to fight with objects full of
getThis, setThat methods I'd wrap them into a generic wrapper with a
__setattr__ and __getattr__ to be able to use attribute get and set as
common sense and decency require, e.g, something like....:


Actually, I prefer the "hasattr" solution. I'm thinking of removing the
setter functionality from the parser. If some class needs to do
specific stuff when a member is updated, as you said, the built-in
function property can still be used.

Regards,
Nicolas
Jul 18 '05 #5

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

Similar topics

4
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned...
2
by: Jonathan | last post by:
I am looking for a simple way to check if a database table exists. I keep getting advice to use "Try.. Catch" and other error handling methods, but I obviously don't want to have to display an...
5
by: Genboy | last post by:
My "VIS" Website, which is a C# site created in VS.NET, Framework 1.1, is no longer compiling for me via the command line. As I have done 600 times in the last year and a half, I can compile to...
11
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you...
2
by: www.MessageMazes.com | last post by:
Greetings, I'm experimenting with an ASP page that reads data from a file name that is passed to it as a parameter, as in this page, which works, because the "good" file exists. ...
5
by: Gary Wessle | last post by:
hi or is there a better way to check the existence of "py" in a string "s"? string s = "djrfpyfd"; string t = "py"; string r = s.substr(s.find("py"),2); cout << (t==r) << endl;
25
by: pamelafluente | last post by:
Hi Guys, I have the following HTML code which is doing a GET to a page, say MyUrl.aspx : <body> <form name="form1" method="get" action="MyUrl.aspx" id="form1"> <input type="hidden"...
18
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning...
10
by: Dieter Pelz | last post by:
Hallo, what is the best way to check the installation of mfc80 and vcrt sidebyside assemblies? Best Regards, Dieter Pelz
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.