Python's locals() function

Links to the original text: https://www.jianshu.com/u/8f2987e2f9fb

Python's locals() function returns all local variables of the current location in dict type.

Sample code:

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Looking for like-minded partners and helping each other, there are also good video learning tutorials and PDF e-books in the group.
'''
def func():
    arg_a, arg_b = 'a', 'b'

    def func_a():
        pass

    def func_b():
        pass

    def print_value():
        print(arg_a, arg_b)

    return locals()


if __name__ == '__main__':

    args = func()
    print(type(args))
    print(args)

As you can see from the running result, the local variable of function func will be returned as dict type.

<class 'dict'>
{'func_a': <function func.<locals>.func_a at 0x10d8f71e0>, 'arg_b': 'b', 'arg_a': 'a', 'print_value': <function func.<locals>.print_value at 0x10d8f7378>, 'func_b': <function func.<locals>.func_b at 0x10d8f72f0>}

Combining locals() with property to improve code readability

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Looking for like-minded partners and helping each other, there are also good video learning tutorials and PDF e-books in the group.
'''
class NewProps(object):

    def __init__(self):
        self._age = 40

    def fage():
        doc = "The age property."

        def fset(self, value):
            self._age = int(value)

        def fget(self):
            return self._age

        def fdel(self):
            del self._age

        return locals()

    age = property(**fage())

if __name__ == '__main__':
    x = NewProps()
    print(x.age)
    x.age = 50
    print(x.age)

It should be noted here that the four attribute names under the fage() method can not be modified (and other attributes can not be added, unless the dict returned by locals() is processed and the redundant elements are removed), they must be fset, fget, fdel, doc. If the attribute names are changed, the following exception will be thrown:

'f_set' is an invalid keyword argument for this function

Because the _init_ method of property receives four parameters (except self, because the Python compiler automatically passes self in)

def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__
  .....

When returning locals (), dict is returned, the value of key corresponds to the name of the parameter one by one, and the _init_ method of property is passed in the form of ** kwargs parameter.

Of course, a better way is to use a property decorator.

Keywords: Python Attribute

Added by caster001 on Thu, 03 Oct 2019 11:34:05 +0300