Python Forum
How create programmatically variables ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How create programmatically variables ?
#2
(Aug-09-2023, 04:11 AM)SpongeB0B Wrote: I've dig the WWW but I found only very old results that lead to create some Dictionary...
Variables in Python are kept in namespaces, which have a dictionary-like semantics. For example global variables in a module are kept in the globals() dictionary, which you could also access as vars(sys.modules[__name__]). You can update these dictionaries to create module-level variables.

Usually however, this is bad practice and it is better to use another dictionary that your program creates.

I see a good use case for this, which is lazy imports of subpackages in a package Spam:
# Spam.__init__.py

def __getattr__(name):
    from importlib import import_module
    submodule = import_module(name, __package__)
    globals()[name] = submodule
    return submodule
Now in client code
import Spam
# accessing Spam.eggs automatically imports submodule Spam.eggs
Spam.eggs.somefunction()

# on second access, nothing is imported because eggs is now a member of Spam
Spam.eggs.otherfunction()
Even in this example, one could avoid updating globals() directly by using setattr(import_module(__name__), name, submodule), emphasizing that we are "setting an attribute" instead of "creating a variable".

A different example of creating a variable 'eggs' in the Python shell
>>> import sys
>>> module = sys.modules[__name__]
>>> module.eggs = 'Humpty Dumpty'
>>> eggs
'Humpty Dumpty'
Reply


Messages In This Thread
RE: How create programmatically variables ? - by Gribouillis - Aug-09-2023, 07:45 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create X Number of Variables and Assign Data RockBlok 8 1,134 Nov-14-2023, 08:46 AM
Last Post: perfringo
  How to programmatically stop a program in Jupyter Notebook? Mark17 11 38,281 Feb-12-2023, 01:41 PM
Last Post: jp21in
  Create Excel Line Chart Programmatically dee 3 1,257 Dec-30-2022, 08:44 PM
Last Post: dee
  Create array of values from 2 variables paulo79 1 1,167 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  How to create 2 dimensional variables in Python? plumberpy 5 1,978 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  How to programmatically exit without Traceback? Mark17 7 6,526 Mar-02-2021, 06:04 PM
Last Post: nilamo
  Create new variable dependent on two existing variables JoeOpdenaker 6 3,166 Oct-25-2020, 02:15 PM
Last Post: jefsummers
  Adding Language metadata to a PDF programmatically bhargavi22 0 1,989 Aug-17-2020, 12:53 PM
Last Post: bhargavi22
  Create, assign and print variables in loop steven_tr 10 4,506 May-28-2020, 04:26 PM
Last Post: ndc85430
  I can't figure out how to create variables in a while loop MrCag 1 2,438 May-08-2018, 08:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020