views:

99

answers:

2

I'm trying to do the following:

import sys; sys.path.append('/var/www/python/includes')
import functionname

x = 'testarg'
fn = "functionname"
func = getattr(fn, fn)
func (x)

but am getting an error:

"TypeError: getattr(): attribute name must be string"

I have tried this before calling getattr but it still doesn't work:

str(fn)

I don't understand why this is happening, any advice is appreciated

+2  A: 

It sounds like you might be wanting locals() instead of getattr()...

x = 'testarg'
fn = "functionname"
func = locals()[fn]
func (x)

You should be using getattr when you have an object and you want to get an attribute of that object, not a variable from the local namespace.

Joe Kington
thanks.. yeah you are right, I was confused about the usage, I found getattr in a post somewhere saying to do it this way to call a variablized function name but apparently it was not correct
Rick
@Rick, I don't get it, `functionname` is a module, and you _call_ it with a parameter?
gnibbler
@Rick, your assertion that those statements you show in the question produced the exceptions you shown remains a bare-faced lie, **whatever** may be in the `functionname.py` you're importing (net of absurdities like it overwriting the `getattr` built-in of course).
Alex Martelli
Theres no need to make personal attacks, why would I lie about this, as if I enjoy wasting my time and others on stackoverflow? The module anme and functioname are the same which is what I always do, to answer your question, gnibbler.. perhaps I made some mistake but i already moved on past this issue by doing some other workaround but saying i am lying is ridiculous, maybe I am somehow wrong but I am not lying about anything
Rick
A: 

The first argument of getattr is the object that has the attribute you are interested in. In this case you are trying to get an attribute of the function, I assume. So the first argument should be the function. Not a string containing the function name, but the function itself.

If you want to use a string for that, you will need to use something like locals()[fn] to find the actual function object with that name.

Second, you're passing the function name to getattr twice. The function doesn't have itself as an attribute. Did you mean the second argument to be x? I don't really get what you're trying to do here, I guess.

kindall
its from an import so thats why its like that, I updated the OP
Rick