Home > OS >  Is it reasonable to use a blank class like a dictionary? Why would someone have done it?
Is it reasonable to use a blank class like a dictionary? Why would someone have done it?

Time:12-17

I am working on an old Python codebase. I am not in contact with anyone who had worked on the codebase previously, so I do not know why the previous developers did what they did.

In the codebase, there is a "blank" class which is used in a similar way as a dictionary. Here is a simplified example.

# Defining a "blank" class
class blank:
 pass

items = blank()

# There is a function to "add" to items by using setattr

def addItem(name, item):
 setattr(items, name, item)

addItem("att1", obj1)
addItem("att2", obj2)

# Later, items is used like this
items.att1.someFunction()
items.att2.otherFunction()

What are the advantages or disadvantages, if any, of using a class in this way instead of a dictionary?

CodePudding user response:

It's quaint, but it works and nothing goes wrong. If I could say anything against it, it's that you may as well just use a dict directly and use getitem/setitem syntax instead of getattr/setattr. There is a slight code smell of homesick javascript developers.

The replacement in modern Python (version 3.3 ) is using a types.SimpleNamespace, instance, documented under Additional Utility Classes and Functions:

SimpleNamespace may be useful as a replacement for class NS: pass.

  • Related