Answer the question
In order to leave comments, you need to log in
Is it possible to make a variable global in a function?
For example, I am writing a bot in python + aiogram, and I need to use a variable that was in the code earlier (in some of the functions). Are there ways to do this?
I had an idea to make the variable I need global in the standard way (global), but in this case the variable should be outside the function, which doesn’t seem to suit me
Answer the question
In order to leave comments, you need to log in
In general, global variables are bad and in some cases lead to typical, but difficult to detect and non-obvious bugs.
If you need different calls to different functions to have access to the same variable, you need to pass the context to these functions. The context can be an object, where everything necessary is added in the form of arguments.
You need to remember the need to correctly and timely initialize the context.
I think aiogram has a regular way of passing context to handlers, but in simple cases it is enough to make a global variable and initialize the context in it at startup. This way you don't have to declare it as global in functions, it will be found when traversing namespecs.
The assignments will be inside the context, and the global variable will remain unchanged.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question