Functionality like local static in C

Chris Angelico rosuav at gmail.com
Thu Apr 14 14:19:32 EDT 2022


On Fri, 15 Apr 2022 at 03:53, Sam Ezeh <sam.z.ezeh at gmail.com> wrote:
>
> I've seen people use function attributes for this.
> ```
> Python 3.10.2 (main, Jan 15 2022, 19:56:27) [GCC 11.1.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def function():
> ...     print(function.variable)
> ...     function.variable += 1
> ...
> >>> function.variable = 1
> >>> function()
> 1
> >>> function()
> 2
> >>>
> ```
>
> If necessary, the variable can be initialised inside the function too.
>

Indeed; or you can initialize it with a decorator:

def static(**kw):
    def deco(f):
        for name, val in kw.items():
            setattr(f, name, val)
        return f
    return deco

@static(variable=1)
def function():
    print(function.variable)
    function.variable += 1

There are a good few quirks to the concept of "static variables"
though, and how you perceive them may guide your choice of which style
to use. For example, what should this do?

def outer():
    def inner():
        static variable = 1
    return inner

Should it have a single static variable shared among all the closures?
If so, you probably want a global. Should each closure have its own
static? Then use nonlocal and initialize the variable in outer(). Or
what about methods?

class Spam:
    def ham(self):
        static variable = 1

Shared across them all? Use Spam.variable, which (being attached to
the class) is common to all Spam instances. Unique to each instance?
Well, that's exactly what object members are, so "self.variable" is
perfect.

There are other quirks too (like decorated functions that end up
wrapped, multiple classes, inheritance, etc etc etc), and honestly, if
you don't care about those use cases, go with whichever one seems most
convenient at the time :)

ChrisA


More information about the Python-list mailing list