Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a group of related variables in Python?

Tags:

python

In JavaScript, I like to define my variables in objects so that it is clear (to me, at least) that all of it's properties are related.

For example:

var box = {
  width: 100,
  height: 200,
  weight: 80
}

Is there a way to do something similar in python?

like image 557
Raphael Rafatpanah Avatar asked Dec 18 '22 09:12

Raphael Rafatpanah


2 Answers

This is called a dict or dictionary in python the syntax is almost identical:

box = {
  'width': 100,
  'height': 200,
  'weight': 80
}

you can later access these values like this:

box['width']
like image 126
Nullman Avatar answered Feb 14 '23 12:02

Nullman


Grouping using the dictionary is only one of the ways to do it. If you like a.b attribute access syntax more, you could use one of the following:

Module

You could do it using the module, for example put them to something named settings.py:

width = 100
height = 200
weight = 80

Then you could use it like this:

import settings
area = settings.width * settings.height

But modules in Python are singletons, so if you change settings.width in one place - it will change in all the others.

Class

Also you could do grouping using class attributes:

class Box:
    width = 100
    height = 200
    weight = 80

print(Box.width) # 100

# You could use instances to update attributes on separate instance
box = Box()
print(box.width) # 100
box.width = 10
print(box.width) # 10

# But their original values will still be saved on class attributes
print(Box.width) # 100

namedtuple

Another option is to use collections.namedtuple.

from collections import namedtuple

Box = namedtuple('Box', ('width', 'height', 'weight'))
box = Box(100, 200, 80)
print(box.width) # 100

# Tuples are immutable, so this is more like a way to group constants
box.width = 10 # AttributeError: can't set attribute
like image 28
Bunyk Avatar answered Feb 14 '23 12:02

Bunyk