What is the Python equivalent of static variables inside a function?

前端 未结 26 2797
天命终不由人
天命终不由人 2020-11-22 00:45

What is the idiomatic Python equivalent of this C/C++ code?

void foo()
{
    static int counter = 0;
    counter++;
          


        
26条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:22

    I personally prefer the following to decorators. To each their own.

    def staticize(name, factory):
        """Makes a pseudo-static variable in calling function.
    
        If name `name` exists in calling function, return it. 
        Otherwise, saves return value of `factory()` in 
        name `name` of calling function and return it.
    
        :param name: name to use to store static object 
        in calling function
        :type name: String
        :param factory: used to initialize name `name` 
        in calling function
        :type factory: function
        :rtype: `type(factory())`
    
        >>> def steveholt(z):
        ...     a = staticize('a', list)
        ...     a.append(z)
        >>> steveholt.a
        Traceback (most recent call last):
        ...
        AttributeError: 'function' object has no attribute 'a'
        >>> steveholt(1)
        >>> steveholt.a
        [1]
        >>> steveholt('a')
        >>> steveholt.a
        [1, 'a']
        >>> steveholt.a = []
        >>> steveholt.a
        []
        >>> steveholt('zzz')
        >>> steveholt.a
        ['zzz']
    
        """
        from inspect import stack
        # get scope enclosing calling function
        calling_fn_scope = stack()[2][0]
        # get calling function
        calling_fn_name = stack()[1][3]
        calling_fn = calling_fn_scope.f_locals[calling_fn_name]
        if not hasattr(calling_fn, name):
            setattr(calling_fn, name, factory())
        return getattr(calling_fn, name)
    

提交回复
热议问题