Python Forum
Generate Python variables dynamically
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generate Python variables dynamically
#3
If you have an object you can set attributes for the object
import junk

for name, value in zip('abc', (1, 2, 3)):
    setattr(junk, name, value)

print(junk.a, junk.b, junk.c)
Output:
1 2 3
What I don't know is how to get the module for the file you are in. I suppose you could use locals() or globals().
globals()['a'] = "I am a global a"
locals()['b'] = "I am a global b"

def func():
    locals()['b'] = "I am local b"
    locals()['c'] = "I am local c"
    print(a)
    print(b)
    print(c)

print(a)
print(b)

func()
Output:
I am a global a I am a global b I am a global a I am a global b Traceback (most recent call last): File "...", line 14, in <module> func() File "...", line 9, in func print(c) NameError: name 'c' is not defined
Looks like locals() doesn't create variables in the local scope of the function. Not surprising.

I cannot fathom why you would ever want to do this. A variable is a convenient name you can use to access an object. Dynamically created names are not going to be convenient.
Reply


Messages In This Thread
RE: Generate Python variables dynamically - by deanhystad - Mar-03-2022, 05:24 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with Python Script to generate SVG Dot Matrix Pattern for LED Light Guide iamrickm 2 856 Aug-25-2023, 06:07 PM
Last Post: iamrickm
  Generate RPM package from a Python + Kivy application for an "offline" installation pruvosim 2 2,295 Jun-04-2020, 12:16 PM
Last Post: pruvosim
  generate UML design from python code Phaze90 2 2,554 Apr-13-2020, 11:36 AM
Last Post: Phaze90
  generate random variables based on a non-standard t-distribution nathalie 4 3,527 Dec-03-2019, 12:11 AM
Last Post: scidam
  How can one generate triangular and sawtooth waves in python? xBlackHeartx 6 13,825 Sep-25-2019, 11:52 PM
Last Post: metulburr
  Generate a report in Python qureshi 2 3,700 Aug-24-2019, 04:50 AM
Last Post: ndc85430
  I need help using Python to generate usernames and passwords with excel documents Jannejannesson 3 4,092 May-08-2019, 02:30 PM
Last Post: Jannejannesson
  How to generate calendar with 2 formats in python luizcrf 1 2,740 Nov-01-2018, 06:46 AM
Last Post: Larz60+
  How to generate more MP3 files at the same time in Amazon Polly using Python code? makiwara 2 3,834 Jul-02-2018, 08:43 PM
Last Post: makiwara
  how to generate sha256 hash for each line of my txt file | using python version 3.6.4 rajtekken5 2 9,211 Feb-11-2018, 01:41 PM
Last Post: rajtekken5

Forum Jump:

User Panel Messages

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