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

Question:

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?

Asked By: 79037662

||

Answers:

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.

Answered By: wim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.