During development with Django, there was a part I wanted to enjoy using variable names. ~~ I think it's not good code when you want to use variable names in the first place ~~
At first, I wrote this desperately, so when I looked it up, it seems that it can be realized with the ** built-in function locals () **.
def hoge(name, email, message):
for variable_name, value in zip(("name", "email", "message"), (name, email, message)):
print(f"{variable_name} -> {value}")
... but it's terrible.
Looking at the document ... https://docs.python.org/ja/3/library/functions.html#locals
Updates and returns a dictionary representing the current local symbol table. Free variables are returned when you call locals () in a function block, but not in a class block. Note that at the module level, locals () and globals () are the same dictionary.
Annotations Do not change the contents of this dictionary; changes do not affect the values of local or free variables used by the interpreter.
a. In short, the variable and value of the scope of the called location will be returned as a dict. And that value cannot be changed. It turned out that the variable name can be obtained by str by extracting the key of this dict.
Suppose you have a code like this:
class Account(object):
param = "param"
print(locals()) #Execution order 1
def __init__(self, name, email):
self.name = name
self.email = email
print(locals()) #Execution order 2
def some_function(self, param1, param2):
self.param1 = param1
self.param2 = param2
print(locals()) #Execution order 3
account = Account("ragnar", "[email protected]")
account.some_function(1, 2)
print(locals()) #Execution order 4
print(type(locals())) #Execution order 5
The execution result of the above code is as follows. You can get the variable of the scope of the place to print. The return value is dict.
{'__module__': '__main__', '__qualname__': 'Account', 'param': 'param'}
{'self': <__main__.Account object at 0x1065e6990>, 'name': 'ragnar', 'email': '[email protected]'}
{'self': <__main__.Account object at 0x1065e6990>, 'param1': 1, 'param2': 2}
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10652a190>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
'__file__': '/Users/ragnar/workspace/class/locals.py', '__cached__': None,
'Account': <class '__main__.Account'>, 'account': <__main__.Account object at 0x1065e6990>}
<class 'dict'>
The return value is an ordinary dict, so you can get it by using keys or items. The first example can be rewritten as:
def hoge(name, email, message):
for variable_name, value in locals().items():
print(f"{variable_name} -> {value}")
Getting variable names in a list is like this.
def hoge(name, email, message):
ls = [key for key in locals().keys()]
To be honest, I don't think there are many situations where you want the variable name str, but I came up with one.
↓ Such a code
class Account(object):
def __init__(self, name, email, sex, age):
self.name = name
self.email = email
self.sex = sex
self......
If you use this as a variable name, it will look like this.
class Account(object):
def __init__(self, name, email, sex, age):
for variable_name, value in locals().items():
if not variable_name == 'self':
self.__dict__[variable_name] = value
...... I don't use it unless the argument is insanely long.
-Get the variable name using locals () ・ Try to make the code easier to read than to enjoy
Recommended Posts