Simple Namespace

Python's SimpleNamespace is a utility for creating simple object types. It's part of the types module in the Python Standard Library and provides a way to quickly and simply create a "dot notation" namespace for a collection of attributes.

Python's SimpleNamespace is a utility for creating simple object types. It's part of the types module in the Python Standard Library and provides a way to quickly and simply create a "dot notation" namespace for a collection of attributes.

Let's use TSLA, my favourite stock as an example:

stock_dict = {
    "ticker": "TSLA",
    "open": 124.65,
    "previous_close": 124.65,
    "trade_high": 124.67,
    "trade_low": 122.97,
    "year_high": 129.03,
    "year_low": 83.34,
    "dividend_yield": None,
    "currency": "USD"
}

That's self explanatory, we import the library and declare a dictionary that contains  some attributes.

We can choose to use it in the traditional way e.g. stock_dict["ticker"] or we can employ SimpleNamespace to get a slightly cleaner visual.

from types import SimpleNamespace


stock = SimpleNamespace(**stock_dict)

print(f"{stock.ticker} opened at {stock.open} {stock.currency}")

... which will print:

TSLA opened at 124.65 USD
Note that SimpleNamespace is mutable. e.g you could do:
stock.trade_high = 129.01 and it would be perfectly happy.

At this point, one could ask "should we be using a class? Perfectly valid question and one that can only be answered by the complexity of your program.

Should you wish something quick and clean that requires no behaviour, then you can use a simple data structure such as SimpleNamespace. If you need getters and setters, properties, the ability to pass models around and do a lot of funky stuff then classes would be your goto object (unless you are into functional programming but I will not open that can of worms right now).

Capisce?

Some Thoughts (based on feedback)

My friend Bob was asking, how about a namedtuple or even dataclass? There could be other considerations, since python has a plethora of data structures.

Here's my very opinionated response:

  • Use named tuples when you need immutability.
  • Use data classes when you want all the freebies one gets with a data class and the lovely __post_init__. I love that thing.
  • Use classes when you want behaviours.
  • Use simple namespaces when you are doing an early prototype, want clean dot notation, you're not sure about mutability, until you figure out what's the best data structure to use.
  • Dictionaries are good. Less quotes and square brackets are good too.

    We'll talk about all that and much more eventually. Ultimately the decision is yours and only yours.

Alright, see you on the next one.