On Jul 30, 11:57 am, "Russ P." <[EMAIL PROTECTED]> wrote: > On Jul 29, 6:33 pm, "Russ P." <[EMAIL PROTECTED]> wrote: > > > > > On Jul 29, 1:40 pm, kj <[EMAIL PROTECTED]> 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 > > > -- > > > NOTE: In my address everything before the first period is backwards; > > > and the last period, and everything after it, should be discarded. > > > If the constant parameters are really only needed in one particular > > function, you can use default function arguments. An added benefit is > > that you can override them with another value if necessary. > > > def fun(x, y, parameter1=0, parameter2=1): > > ... > > I should add that the parameters need not be literal numbers. They can > be computed values as well. They will be computed only once, on the > first pass through the function definition, which I presume is exactly > what you want. > > I think this is the simplest solution to the problem you posed.
Here's a real-life example, where the second and third args are run- time constants: def unescape(s, subber=re.compile(r'_x[0-9A-Fa-f]{4,4}_').sub, repl=lambda mobj: unichr(int(mobj.group(0)[2:6], 16)), ): if "_" in s: return subber(repl, s) return s # The if test is just an optimisation that unfortunately the re module doesn't nut out for itself. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list