Skip to content
Advertisement

Alternatives to attrdict library for nested AttrDict

My program contains a lot of configuration parameters so I was looking for a way to have them all in one place, accessible from every file in the project. I thought about a config module which would act as an interface to a yaml file that contains the configuration parameters. One requirement I want is to be able to access the config object with attribute (dot) notation. I found the AttrDict library and wrote the following code:

JavaScript

The problem is that this library does not allow nested AttrDict().

JavaScript

However if I do the following, nested assignment works but I’m forced to explicitly use the nested object which is not useful for my purpose:

JavaScript

Advertisement

Answer

I’ve looked into the documentation of AttrDict and I’m afraid that recursive attribute access is not possible. See here:

Recursive attribute access results in a shallow copy, so recursive assignment will fail (as you will be writing to a copy of that dictionary):

JavaScript

They suggest using an AttrMap instead. However I’ve tried using it and I was getting an error right from the import. I’ll look into it. *update below

For now, what you can do is define instead your custom AttrDict.

JavaScript

The output here is, as you needed:

JavaScript

If you are using an IDE you will also get code completion while you access the keys of AttrDict.

See also here, there are additional methods you can add to the custom class that can enhance its functionalities.

Hope this helps!

Update on the AttrMap library. I’ve asked about it here, I was using python 3.8 but the library contains a list[str], which is available only on python >= 3.9.

Second update on AttrMap. The creator has fixed the issue in the new version, now it supports python 3.6

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement