Python Forum
How create programmatically variables ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How create programmatically variables ?
#5
As mention use data stucture eg a @dataclass() is a simple way.
from dataclasses import dataclass

@dataclass()
class Var:
    x: float
    y: float
    z: int = 1

var = Var(1.5, 2.5)
print(var)
Output:
Var(x=1.5, y=2.5, z=1)
So data is mutable and can change as wish.
If want it immutable just add @dataclass(frozen=True).
>>> var.x = 100.4
>>> var.x
100.4
>>> var
Var(x=100.4, y=2.5, z=1)
The data is also stored in dictionary,to see this can call like this.
>>> var.__dict__
{'x': 100.4, 'y': 2.5, 'z': 1}
Just to clarify this is this same as making variables like this.
>>> x = 100.4
>>> y = 2.5
>>> z = 1
Now will these variables go into globals dictionary,as Gribouillis show some examples of.
But should not mess with globals and use normal visible data structure as eg shown here.
If you unfamiliar with dataclass,here is the same as a ordinary class.
class Var:
    def __init__(self, x: float, y: float, z: int = 1):
        self.x = x
        self.y = y
        self.z = z

    def __repr__(self):
        return f"Var(x={self.x}, y={self.y}, z={self.z})"

var = Var(1.5, 2.5)
print(var)
Output:
Var(x=1.5, y=2.5, z=1)
Reply


Messages In This Thread
RE: How create programmatically variables ? - by snippsat - Aug-09-2023, 03:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create X Number of Variables and Assign Data RockBlok 8 1,060 Nov-14-2023, 08:46 AM
Last Post: perfringo
  How to programmatically stop a program in Jupyter Notebook? Mark17 11 37,911 Feb-12-2023, 01:41 PM
Last Post: jp21in
  Create Excel Line Chart Programmatically dee 3 1,246 Dec-30-2022, 08:44 PM
Last Post: dee
  Create array of values from 2 variables paulo79 1 1,137 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  How to create 2 dimensional variables in Python? plumberpy 5 1,950 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  How to programmatically exit without Traceback? Mark17 7 6,447 Mar-02-2021, 06:04 PM
Last Post: nilamo
  Create new variable dependent on two existing variables JoeOpdenaker 6 3,144 Oct-25-2020, 02:15 PM
Last Post: jefsummers
  Adding Language metadata to a PDF programmatically bhargavi22 0 1,971 Aug-17-2020, 12:53 PM
Last Post: bhargavi22
  Create, assign and print variables in loop steven_tr 10 4,470 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,414 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