dynamic construction of variables / function names
bruno at modulix
onurb at xiludom.gro
Thu Mar 30 04:39:54 EST 2006
Steven D'Aprano wrote:
> Sakcee wrote:
>
>> python provides a great way of dynamically creating fuctions calls and
>> class names from string
>>
(snip)
> Personally, I think the best way is: find another way to solve your
> problem.
>
See Duncan's post for a pretty clean and pythonic solution. Another one
that may be more explicit and avoid messing with locals() or globals() is:
>> is it correct way, is there a simple way, is this techniqe has a name?
>
>
> I'm told that some people call this "dynamic programming",
In some other languages, it could be called 'metaprogramming', but this
is such a common idiom in Python that I'd just call this "programming" !-)
> but
> personally I call it "difficult to maintain, difficult to debug
> programming".
Oh yes ? Why so ? I've used such patterns hundreds of time, and it has
never been a problem so far.
Dynamically selecting the function to call given a name (as string) is
is a well-known programming pattern. I learned this in C, using a
hashtable to store names/function pointer pairs. And that's mostly what
the proposed solutions (the one based on globals() or locals() as well
as Duncan's class-based one) do - the main difference being that Python
offers the hashtable for free !-)
nb : I agree that the use of the global or local namespaces may not be
the best thing to do - better to use (any variant of) Duncan's solution
IMHO.
> (Before people get all cranky at me, I'm aware that it isn't *always*
> the Wrong Way to solve problems, but it is a technique which is subject
> to abuse and can often be avoided by using function objects instead of
> function names.)
When you get the function name as user input, you cannot directly access
the function object.
And anyway, what do you think Python do when you call a function ?
Python namespaces *are* hash tables mapping symbols names (as string) to
objects (as pointers). I don't see much difference here.
(nb 2 : I agree that it is of course better to avoid 'manual' namespace
lookup whenever possible)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list