[Python] Get the variable name with str

Overview

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.

Built-in function locals ()

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.

Take a look

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'>

Get variable name

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()]

And where can I use it?

To be honest, I don't think there are many situations where you want the variable name str, but I came up with one.

* Isn't it possible to use it in a constructor that tends to use the same variable name as the argument? *

↓ 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.

Conclusion

-Get the variable name using locals () ・ Try to make the code easier to read than to enjoy

Recommended Posts

[Python] Get the variable name with str
How to get the variable name itself in python
Get the weather with Python requests
Get the weather with Python requests 2
Get the host name in Python
Get date with python
[Python] Get the files in a folder with Python
Get git branch name and tag name with python
Get country code with python
Get the variable name of the variable as a character string.
[Python] Get the numbers in the graph image with OCR
Get Youtube data with python
Get the result in dict format with Python psycopg2
[Python] Get the previous month
Get thread ID with python
Get started with Python! ~ ② Grammar ~
Call the API with python3.
Get the operation status of JR West with Python
Get stock price with Python
Get home directory with python
Get keyboard events with python
Get Alembic information with Python
[Python3] Format the character string using the variable name as the key.
When the variable name conflicts with the Devaga command in pdb
Minimum knowledge to get started with the Python logging module
[Python] Get the script execution directory with an absolute path
How to get into the python development environment with Vagrant
System trade starting with Python3: Get the latest program code
Try to decipher the garbled attachment file name with Python
[Introduction to Python] How to get data with the listdir function
Get the host name of the host PC with Docker on Linux
Get the source of the page to load infinitely with python.
Extract the xz file with python
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Get reviews with python googlemap api
Get the desktop path in Python
Get web screen capture with python
[Python] Get economic data with DataReader
Get the script path in Python
How to get the Python version
Find the Levenshtein Distance with python
How to get started with Python
Hit the Etherpad-lite API with Python
Install the Python plugin with Netbeans 8.0.2
[Small story] Get timestamp with Python
I liked the tweet with python. ..
Get Qiita trends with Python scraping
Get the desktop path in Python
Master the type with Python [Python 3.9 compatible]
Python Note: Get the current month
Get started with Python in Blender
Get weather information with Python & scraping
How is the progress? Let's get on with the boom ?? in Python
The fastest way to get camera images regularly with python opencv
PhytoMine-I tried to get the genetic information of plants with Python
Get property information by scraping with python
[Python] Set the graph range with matplotlib
[Note] Get data from PostgreSQL with Python
Check the existence of the file with python
[Python] Round up with just the operator