0

I am using class to scope data (yap, maybe I should move this to a 2nd module). This class will contain a lot of "constants", however some of them need to be calculated when the script starts.

It would be great if this static method would be run at startup, without me dealing with that. Is there a function called at class creation? (not object creation!)

class Constants:
    data = {}
    capacity = 0
 
    def createData():
        data[1] = "123!"
        data[2] = "aaa"
        data[3] = "bb"
        for i in a: 
            capacity = capacity + len(i) 


#Constants.createData()
print(f"data[2] = {Constants.data[2]}")

Notes:

  1. The data is deterministic, and computed. I could create a script that creates a python code... but this is ugly.
  2. I will not instantiate this class, instead I am using it as a scope.
  3. Note that capacity needs to be computer at runtime. In my real life application - data is much more randomized, and swapped. I also have MIX/MAX values of arrays (again, arrays are populated at runtime, not "compile/write time"
3
  • Add createData() call at the same level as data and capacity definitions. Commented Apr 28, 2022 at 11:46
  • 2
    If you just want to group some values, use types.SimpleNamespace rather than defining a new class. Commented Apr 28, 2022 at 11:51
  • @chepner and then at global scope of the module (types in your case) do initialization? Commented May 1, 2022 at 7:04

2 Answers 2

2

Use class method for accessing class constants before initiating an instance:

look at this example:

class Test:
    var = 1

    @classmethod
    def fill(cls, value):
        cls.var = value

the result will be:

In [3]: A.var
Out[3]: 1


In [4]: A.fill(2)
In [5]: A.var
Out[5]: 2

So, your code will be:

class Constants:
    data = {}
    capacity = 123
 
    @classmethod
    def createData(cls):
        cls.data['1'] = "123!"
        cls.data['2'] = "aaa"
        cls.data['3'] = "bb"

#Constants.createData()
print(f"data[2] = {Constants.data['2']}")
Sign up to request clarification or add additional context in comments.

1 Comment

In theory - this would be great, but this snippet does not work as you intend. createData(cls) is not called at all.
1

The code inside the class block is what's running at "startup". You can simply do anything you need to do in that code block, or even after it:

class Constants:
    data = {1: "123!"}    # define the data right here
    capacity = 123
 
    data[2] = "aaa"       # ... or here

Constants.data[3] = "bb"  # ... or here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.