getattr problem

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Dec 2 03:48:45 EST 2009


> Victor Subervi wrote:

(NB : answering to the OP - the post didn't show up on clpy)

>> Hi;
>> I have the following code that execute without a problem:

Fine. But it fails to execute here - ImportError on the 3rd line 
("options"), NameErrors on the 4th line ("addStore") and 5th line 
("optionTables").

>> import sys,os
>> sys.path.append(os.getcwd())
>> import options
>> storesTables = []

OT, but the official naming convention in Python is 
all_lower_with_underscores.

>> junkStores = string.join(addStore(), ', ')

junkStores = ", ".join(addStore())

>> for table in optionsTables():

OT again, but a general (not python-specific) naming rule is to use 
nouns for variables and verbs for functions. I almost failed to spot the 
parens after "optionsTables". "getOptionsTables" or something like this 
would make your intent more obvious IM(NS)HO.

>>   if table not in ('particulars', junkStores):

I dont know for sure what junkStores looks like at this point, but given 
the call to string.join, chances are this test doesn't work as expected 
- cf the following snippet:

"""
 >>> foo = ("bar", "baaz, back")
 >>> "bar" in foo
True
 >>> "baaz" in foo
False
 >>>
"""

>>     storesTables.append(table)
>> for table in storesTables:


You don't need two loops here - you could as well proceed as you go, ie:


for table in optionsTables():
    if pass_some_test(table):
        proceed_with(table)


>>   try:
>>     fn = getattr(options, table)
>>     print fn()
>>   except:
>>     pass

AAAARRRGHHH ! NO ! DONT ! EVER ! DO ! THAT !

You have to either *properly* handle and exception OR let it propagate. 
For the record, even sys.exit is implemented as an exception.


>> I need to change the obvious line to this or something similar (that 
>> actually works):
>>
>>     fn = getattr(options, '%s("names")' % table)
>>
>> That is, I need to pass the variable "names" to each table as it is 
>> called.

How does this relate to the above line of code ???????

It really looks like you're programming by accident (IOW : try anything 
until it seems to "work", but without any understanding of what your 
code is *really* doing....)

> How do I do this?

If the question is "how do I pass a variable to a function", then you 
probably didn't write the above code and shouldn't even touch it before 
you learn CS101. Else, please explain more exactly what you're trying to 
do - would be better with an executable, self-contained example.




More information about the Python-list mailing list