Home > Enterprise >  Why strings are not read correctly using easydict?
Why strings are not read correctly using easydict?

Time:02-13

I use the easydict library to set the configurations, but when I store the configuration as strings, it turns the string into a list of the string itself, as follows:

from easydict import EasyDict
conf = EasyDict()
conf.name = 'CD Group'
print(conf.name)

> ['CD Group']    # a list

But what I hope to achieve is:

> CD Group    # string type

Why is it like this? Thanks for any feedback!

easydict source

An interesting point is that when I pass the configuration from the argparse into the easydict, the type doesn't get an error, as follow:

conf.file_name = args.file_name    # --file_name input.xlsx
print(conf.file_name)

> input.xlsx

CodePudding user response:

looking at __setattr__

    def __setattr__(self, name, value):
        if isinstance(value, (list, tuple)):
            value = [self.__class__(x)
                     if isinstance(x, dict) else x for x in value]
        elif isinstance(value, dict) and not isinstance(value, self.__class__):
            value = self.__class__(value)

as you can see in __setattr__ method , if you pass a variable as list or tuple , you get a list, if not you get the original type back.

and I don't have the problem you are mentioning :

conf = EasyDict()
conf.name = 'CD Group'
conf.name2 = ['CD Group']
print(conf.name , conf.name2, sep='\n')

output:

>>
CD Group
['CD Group']
  • Related