Python global variable in another module

Руководство по глобальным переменным

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

С другой стороны, переменная, объявленная внутри определенного блока кода, будет видна только внутри этого же блока — она называется локальной.

Разберемся с этими понятиями на примере.

Пример локальных и глобальных переменных

 
 
def sum(): a = 10 # локальные переменные b = 20 c = a + b print("Сумма:", c) sum()

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

Для решения этой проблемы используются глобальные переменные.

Теперь взгляните на этот пример с глобальными переменными:

 
 
a = 20 # определены вне функции b = 10 def sum(): c = a + b # Использование глобальных переменных print("Сумма:", c) def sub(): d = a - b # Использование глобальных переменных print("Разница:", d) sum() sub()

В этом коде были объявлены две глобальные переменные: a и b . Они используются внутри функций sum() и sub() . Обе возвращают результат при вызове.

Если определить локальную переменную с тем же именем, то приоритет будет у нее. Посмотрите, как в функции msg это реализовано.

 
 
def msg(): m = "Привет, как дела?" print(m) msg() m = "Отлично!" # глобальная переменная print(m)

Здесь была объявлена локальная переменная с таким же именем, как и у глобальной. Сперва выводится значение локальной, а после этого — глобальной.

Ключевое слово global

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

Правила использования global

  • Если значение определено на выходе функции, то оно автоматически станет глобальной переменной.
  • Ключевое слово global используется для объявления глобальной переменной внутри функции.
  • Нет необходимости использовать global для объявления глобальной переменной вне функции.
  • Переменные, на которые есть ссылка внутри функции, неявно являются глобальными.

Пример без использования глобального ключевого слова.

 
 
c = 10 def mul(): c = c * 10 print(c) mul()
line 5, in mul c = c * 10 UnboundLocalError: local variable 'c' referenced before assignment

Этот код вернул ошибку, потому что была предпринята попытка присвоить значение глобальной переменной. Изменять значение можно только с помощью ключевого слова global .

 
c = 10 def mul(): global c c = c * 10 print("Значение в функции:", c) mul() print("Значение вне функции:", c)
Значение в функции: 100 Значение вне функции: 100

Здесь переменная c была объявлена в функции mul() с помощью ключевого слова global . Ее значение умножается на 10 и становится равным 100. В процессе работы программы можно увидеть, что изменение значения внутри функции отражается на глобальном значении переменной.

Глобальные переменные в модулях Python

Преимущество использования ключевого слова global — в возможности создавать глобальные переменные и передавать их между модулями. Например, можно создать name.py, который бы состоял из глобальных переменных. Если их изменить, то изменения повлияют на все места, где эти переменные встречаются.

1. Создаем файл name.py для хранения глобальных переменных:

Источник

How to share global variables between files in Python

How to share global variables between files in Python

Learn how to create global variables that can be shared between files/modules in Python.

Global variables are used in programming to share memory between different sections of an application, this allows for a range of functionality such as keeping track of resource use between classes, storing statistics about an application and much more. In Python, they are mainly used to share values between classes and functions.

Understanding global variables in Python

In Python, a conventional global variable is only used to share a value within classes and functions. A variable- once declared as a global within a function or class can then be modified within the segment.

num = 1 def increment(): global num num += 1 

The above code would allow the variable 'num' to be used within that function, whereas if you were to omit the global statement, it would be undefined.

If you were to attempt to use this logic to declare a global variable from another class however, it would not work as it would in other languages such as Java or C++.

For example, if we had one class with a variable that needed to be accessed from within another imported class, there would be no way for us to access this variable using the global keyword:

import test num = 1 test.increment() 
def increment(): global num num += 1 # num here would still be undefined 

As you can see above, even though we try to access 'num' as a global within the increment() function after it has been given a value in main.py, it will still not be defined and will result in an error.

Sharing global variables between files/modules in Python

Even though the global keyword is conventionally only used to access variables from within the same module, there are ways to use it in order to share variables between files. For example, we could take influence from PHP and create something similar to the "superglobals" variables.

To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.

For example, let's create a function similar to the example above that will increment a global variable. For this we'll need 3 classes to prove the concept; a main class, a class containing our increment function and a class containing the globals.

def initialize(): global num num = 1 
import globals import test if __name__ == "__main__": globals.initialize() print( globals.num ) # print the initial value test.increment() print( globals.num ) # print the value after being modified within test.py 
import globals def increment(): globals.num += 1 

When we run main.py the output will be:

As you can see, once we've initialized the global variable in globals.py, we can then access 'num' as a property from any other module within the application and it will retain its value.

If you're having trouble understanding how this works, feel free to leave a comment below!

Christopher Thornton @Instructobit 5 years ago

Источник

How do I share global variables across modules in Python?

To share global variable across module in Python, let us first understand what are global variables and its scope.

Global Variable

Example

If a variable is accessible from anywhere i.e. inside and even outside the function, it is called a Global Scope. Let’s see an example −

# Variable i = 10 # Function def example(): print(i) print(i) # The same variable accessible outside the function # Calling the example() function example() # The same variable accessible outside print(i)

Output

Share Information Across Modules

Now, to share information across modules within a single program in Python, we need to create a config or cfg module. To form it as a global i.e. a global variable accessible from everywhere as shown in the above example, just import the config module in all modules of your application −

By importing the module in all the modules, the module then becomes available as a global name. Since there is only one instance of each module, any changes made to the module object get reflected everywhere.

Let us now see an example. Here’s config.py

# Default value of the 'k' configuration setting k = 0

Here’s mod.py. This imports the above config:

Here’s main.py. This imports bode config and mod:

import config import mod print(config.k)

Источник

Читайте также:  Java reflection constructor with parameters
Оцените статью