Shed my a light :)

Chris cwitts at gmail.com
Mon Jun 2 07:06:57 EDT 2008


On Jun 2, 12:35 pm, TheSaint <fc14301... at icqmail.com> wrote:
> Hi,
> I using eval for quite strange reason, as long as I don't know a different
> way to implement.
>
> An example:
>
> actions= ('print', 'sum', 'divide', 'myfunction')
> parameters=(5, 'nothing',5.63, object)
>
> for routines in actions:
>      routines(parameters)
>
> I'd like to note that actions are string or string expressions of the program
> functions or python itself, so I've in my program something like:
>
> for nn in actions:
>        eval('cp.%s' %nn)
>
> Where cp is an instance.
>
> So I'm asking here whether exist a way that these string become functions
> inside my program, without using eval()
>
> --
> Mailsweeper Home :http://it.geocities.com/call_me_not_now/index.html

help(getattr)
Help on built-in function getattr in module __builtin__:

getattr(...)
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is
equivalent to x.y.
    When a default argument is given, it is returned when the
attribute doesn't
    exist; without it, an exception is raised in that case.


for nn in actions:
    func = getattr(cp, nn)
    if callable(func):
        func(parameters)

or alternatively

for nn in actions:
    getattr(cp, nn)(parameters)

Hope that helps.



More information about the Python-list mailing list