kj wrote:
Yet another noob question...
Is there a way to mimic C's static variables in Python? Or something
like it? The idea is to equip a given function with a set of
constants that belong only to it, so as not to clutter the global
namespace with variables that are not needed elsewhere.
For example, in Perl one can define a function foo like this
*foo = do {
my $x = expensive_call();
sub {
return do_stuff_with( $x, @_ );
}
};
In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.
Is there an equivalent in Python?
Thanks!
kynn
First names in Python are just that, names that point to objects. Those objects
can contain any type of information including other objects. They are NOT
buckets where things are stored.
1) Names (variables in Perl/C) defined within a Python function are placed in
its local namespace. They are not visible in the global namespace.
2) Yes you can have a local name point to a global. This is often used in
classes with attributes because looking up local is somewhat quicker than
looking up the class attribute.
def foo():
x = expensive_call
return do_stuff_with(x())
In this particular case it doesn't really help.
It would be more useful in something like:
class foo(object):
def __init__(self, initialvalue = 0)
self.currentvalue = initialvalue
def longloopingmethod(self, listtosum):
currentvalue = self.currentvalue
for v in listtosum:
currentvalue += v
BTW - There are BETTER ways to sum a list, so this is just an example.
-Larry
--
http://mail.python.org/mailman/listinfo/python-list