Что возвращает функция locals python
Перейти к содержимому

Что возвращает функция locals python

  • автор:

Использование функции locals() в Python

Сегодня мы рассмотрим использование функции Python locals() . Это еще одна служебная функция, которая очень полезна для отладки вашей программы, которая дает нам текущую локальную таблицу символов в виде словаря.

Python Locals

Что такое таблица символов?

Таблица символов — это таблица, содержащая информацию о различных символах. Здесь символ может означать что угодно — имя переменной, ключевое слово, имя функции и т. д.

Они представляют собой все имена всех переменных, классов и функций в вашей программе.

Как правило, таблица символов состоит не только из имен этих объектов, но и другой полезной информации, такой как тип объекта, область действия и т. д.

Для программы на Python существует 2 типа таблиц символов:

  • Глобальная таблица символов -> хранит информацию, относящуюся к глобальной области действия программы.
  • Таблица локальных символов -> хранит информацию, относящуюся к локальной (текущей) области действия программы.

Это две таблицы символов, определенные на основе глобальной и локальной (текущей) области.

Когда мы обращаемся к локальной таблице символов, мы обращаемся ко всей информации в нашей текущей области, когда интерпретатор выполняет наш код построчно.

Что именно делает функция locals()?

Теперь функция locals() просто вставляет информацию из локальной таблицы символов в консоль в той области, откуда был вызван locals() !

Это, естественно, означает, что вывод locals() будет словарем всех имен переменных и атрибутов, области видимости и т. д.

Например, если у вас есть файл с именем main.py Давайте поместим locals() в качестве нашего единственного оператора и посмотрим, что произойдет. Мы должны получить всю связанную информацию в main области видимости (в данном случае она такая же, как и в глобальной области видимости).

Что ж, мы могли видеть некоторые атрибуты main модуля (Global Scope), который также включает некоторые детали пакета!

Как некоторые из вас могут сразу понять, это то же самое, что и globals() , поскольку оба относятся к одной и той же глобальной области.

Вызов locals() внутри функции

Давайте рассмотрим простую функцию fun(a, b) , которая принимает два аргумента a и b и возвращает сумму. Мы вызовем locals() непосредственно перед возвратом функции.

Здесь есть заметное изменение внутри fun(a, b) . Здесь локальная таблица символов состоит только из имен, связанных с этой функцией.

Поскольку локальная область видимости не является частью пакета, информация о пакете отсутствует и содержит только переменные, связанные с функцией, плюс аргументы.

Также обратите внимание, что глобальная переменная global_var является частью глобальной таблицы символов и в результате отсутствует в локальной таблице символов!

Вызов locals() внутри класса

Это похоже на вызов из функции, но будет содержать все методы класса и соответствующие атрибуты.

Давайте быстро взглянем на пример.

Здесь мы будем вызывать locals() внутри класса после того, как определим все методы класса. Таким образом, эти методы класса также должны быть частью локальной таблицы символов.

Когда мы вызываем locals() из тела класса, мы получаем имя модуля, имя класса и переменные класса. В глобальной таблице символов ничего подобного, как и ожидалось, нет.

Вывод

В этой статье мы узнали, как получить информацию из локальной области видимости с помощью функции locals() . Это возвращает словарь всех полезных имен и атрибутов из локальной таблицы символов и очень полезен для отладки.

locals()

Возвращает словарь, представляющий текущую локальную таблицу символов.

Обновляет и возвращает словарь с текущей локальной таблицей символов. Если функция вызвана внутри другой функции, то она возвращает также свободные (объявленные вне функции, но используемые внутри неё) переменные.

Параметры ¶

  • Функция locals() не принимает никаких параметров.

Возвращаемое значение ¶

  • Функция locals() возвращает словарь текущей локальной таблицы символов.

Примеры ¶

Мы используем файлы cookie

Наш сайт использует файлы cookie для улучшения пользовательского опыта, сбора статистики и обеспечения доступа к обучающим материалам. Мы также передаем информацию об использовании вами нашего сайт партерам по социальным сетям, рекламе и аналитике. В свою очередь, наши партнеры могут объединять ее с другой предоставленной вами информацией, или с информацией, которую они собрали в результате использования вами их услуг.

Функция locals() в Python

Функция locals() в Python возвращает словарь, представляющий текущую локальную таблицу символов.

Программа Python хранит информацию о программе в таблицах символов. Есть два типа таблиц символов:

  • Таблица локальных символов – хранит информацию, относящуюся к локальной области действия программы. Мы можем получить эту деталь, используя функцию locals().
  • Глобальная таблица символов – хранит информацию, относящуюся к глобальной области действия программы. Мы можем получить эту деталь с помощью функции globals().

Таблица символов в Python содержит подробную информацию об именах переменных, методах, классах и т.д.

Функция Python locals() не принимает никаких аргументов. Посмотрим словарь, возвращаемый функцией locals().

Если вы выполните print (globals()), вы получите тот же результат. Однако результат может немного отличаться в зависимости от вашей установки Python.

Так в чем же разница между locals() и globals()? Нет никакой разницы, потому что мы выполняем locals() и globals() в самом текущем модуле. Разница будет присутствовать, когда мы вызовем эти функции внутри метода или класса.

locals() внутри метода

Давайте посмотрим, что будет на выходе, когда locals() и globals() вызываются внутри тела функции.

Итак, ясно, что locals() внутри функции возвращает локальную переменную, обратите внимание, что глобальные переменные являются частью глобального словаря таблицы символов.

locals() внутри класса

Давайте посмотрим на результат, когда locals() вызывается внутри тела класса.

При вызове внутри тела класса locals() содержит имя модуля, имя класса и переменные класса.

Заключение

Функция Python locals() в основном используется для отладки. Мы можем проверить, какие переменные присутствуют в локальной области и их значения. Мы также можем изменить их значения, поскольку это словарь, хотя это не рекомендуется.

6 Examples to Demystify Python locals() Function

Python locals

In python, we have discussed many concepts and conversions. But sometimes, we come to a situation where we need to return the dictionary according to the current local symbol table. In this tutorial, we will be discussing the concept of the python locals() function, which is used to updates and returns a dictionary of the current local symbol table.

What is locals() function in Python?

Python locals() function is an in-built function used to update and return a dictionary of the current local symbol table. It is mostly used for debugging purposes. With the help of this function, We can check what variables are present in the local scope and their values. The local scope is within the function, within the class, etc.

Symbol Table: A symbol table is a type of data structure maintained or created by a compiler used to store all necessary information about the program. These include all the variable names, methods, classes, etc.

Local Symbol Table: The table is used to store all the information needed to the local scope of the program, and this information can be accessed using the built-in function locals().

Syntax

Parameters

It does not take any parameter.

Return value

It returns the dictionary associated with the current local symbol table.

Examples of locals() function in Python

Here, we will be discussing all the examples of the built in locals() function in python:

1. Using locals() function in Python

In this example, we will try to print directly the locals() function with the help of the print function in python. locals() function will directly paste the Local Symbol Table information on the console, on that scope where locals() was called from! Let us look at the example for understanding the concept in detail.

Output:

Using locals() function in Python

Explanation:

  • Here, we will directly print the given function with the help of the print function.
  • locals() function will directly paste the Local Symbol Table information on the console, on that scope where locals() was called from!
  • Hence, we obtain the required dictionary.

2. Using Python locals() function inside local scope

In this example, we will be using the function inside the local scope of the program. In this, we will be creating the two functions and then call the locals() function. Let us look at the example for understanding the concept in detail.

Output:

locals() function inside local scope

Explanation:

  • Firstly, we will make two functions i.e NotPresent() and present().
  • Inside, the Notpresent() function we will directly return the values of locals() function.
  • Inside, the present() function we will put present equals to True and return locals() function.
  • Hence, we will see the output of both the function made.

3. Updating dictionary values by Python locals() Function

In this example, we will be updating locals() dictionary values. Let us look at the example for understanding the concept in detail.

Output:

 Updating dictionary values

Explanation:

  • Firstly, we will make the localsPre() function in the code.
  • Then, we will define that function with str equals to True and print the value of str.
  • After that, we will try to update locals() dictionary values by putting str equals to False.
  • At last, we will see the output.
  • Hence, you can see the output.

4. Python locals() function for global environment

In this example, we will be printing both the locals() function and the globals() function. Through this, we will be telling you that the local symbol table is the same as the global symbol table in the case of the global environment. Let us look at the example for understanding the concept in detail.

Output:

locals() function for global environment

Explanation:

  • Firstly, we will print the locals() function.
  • Then, we will print a new line.
  • At last, we will print the globals() function.
  • Hence, we can see that the local symbol table is the same as the global symbol table in the case of the global environment.

5. Using locals() function inside a class

In this example, we will be using the locals() function inside the class. We will declare the class name with python and inside the class, we will take a variable num which will be having the value 100. Then, we will call the locals() function and see the output. Let us look at the example for understanding the concept in detail.

Output:

inside a class

Explanation:

  • Firstly, we will declare a class with name python.
  • Inside the class, we will declare a variable num which is equal to 100.
  • Then, we will call the locals() function inside the class only.
  • At last, we will be seeing the output.

6. Using locals() with list comprehension

In this example, we will be using the function in a list comprehension. But, the function has its own set of local variables as it is in a separate scope – thus yielding this unexpected behaviour. Let us look at the example for understanding the concept in detail.

Output:

locals() with list comprehension

Explanation:

  • Firstly, we will declare the list as lang with some languages in computer science.
  • We will then be applying the locals() function in the list comprehension and storing the output in the newlist.
  • At last, we are trying to print the new list.
  • Hence, we can see that the output shows unexpected behavior as the list comprehension has its own set of local variables.

Difference between locals(), globals() and vars() function

locals() function

Python locals() function is an in-built function used to update and return a current local symbol table dictionary.

globals() function

Python globals() function is an in-built function used to update and return a dictionary of the current global symbol table.

Get the in-depth knowledge about the python globals() function.

vars() function

Python vars() function is an in-built function used to return a dictionary of the current namespace or the dictionary of argument. The main difference between vars() and locals() is that vars() can take an argument and return a dictionary for the requested object.

Get the in-depth knowledge about the python vars() function.

If we write the locals() function and globals() function in the global environment, they will result in the same output. So, we will be taking an example with the help of function.

Output:

Calling locals() in a function not intuitive?

In this example, we will see that calling a function is not intuitive. I thought the output would be like locals_1 would contain var; locals_2 would contain var and locals_1; and locals_3 would contain var, locals_1, and locals_2. But, the output is something else when I run the code. Let us look at the example for understanding the concept in detail.

Output:

How to find keys in locals() python?

We can find keys in locals() python with the given code. As locals() returns a dictionary, you can use keys() to get all keys.

Output:

Conclusion

In this tutorial, we have discussed the concept of the built-in locals() function in python. We have seen what the locals() function, symbol table, and local symbol table is. Then, we have explained to you the syntax, parameter, and return value of the function. At last, we have explained the concept in detail with the help of different examples. All the examples are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *