I
I
Ivan2021-10-31 01:11:28
Python
Ivan, 2021-10-31 01:11:28

How to set a global dynamic variable name?

There is a telegram bot with which you can remotely run selenium and perform some kind of functionality, but if another user uses this bot, then everything breaks down, the only solution I found is to assign a unique name to each instance.

The only condition is that the instance must be globally visible

@dp.message_handler(lambda message: message.text == "Авторизоваться")
async def login(message: types.Message):
  user_id = message.from_user
  ozon_user = 'ozon_user_{0}'.format(user_id['id'])
  globals()[ozon_user] = browser.OzonBrowser(user_id['id'])
  markup = types.ReplyKeyboardRemove()
  await Form.login.set()
  await message.reply("Укажи логин для входа начиная 9", reply_markup=markup)


At the output, I expected several instances of the OzonBrowser class with the name of a variable of the format ozon_user_82763478, ozon_user_514189124, etc.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
antares4045, 2021-10-31
@FCKJesus

actually, the piece of code from the question is completely valid and the line
globals()[VariableName] = VariableValue
really creates a global variable -- if it doesn't work for you, then you're looking in the wrong place.
But, I will join Sergey: it is better to create a global dictionary and put it into it.

ozonBrowsers = dict()
@dp.message_handler(lambda message: message.text == "Авторизоваться")
async def login(message: types.Message):
  user_id = message.from_user
  ozon_user = 'ozon_user_{0}'.format(user_id['id'])
  ozonBrowsers[ozon_user ] = browser.OzonBrowser(user_id['id'])
  markup = types.ReplyKeyboardRemove()
  await Form.login.set()
  await message.reply("Укажи логин для входа начиная 9", reply_markup=markup)

S
Sergey Gornostaev, 2021-10-31
@sergey-gornostaev

Vocabulary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question