Giter Site home page Giter Site logo

infinidat / munch Goto Github PK

View Code? Open in Web Editor NEW

This project forked from dsc/bunch

759.0 25.0 84.0 164 KB

A Munch is a Python dictionary that provides attribute-style access (a la JavaScript objects).

Home Page: http://github.com/Infinidat/munch

License: MIT License

Makefile 0.97% Python 99.03%

munch's Introduction

Latest Version Supported Python versions Downloads

munch

Installation

pip install munch

Usage

munch is a fork of David Schoonover's Bunch package, providing similar functionality. 99% of the work was done by him, and the fork was made mainly for lack of responsiveness for fixes and maintenance on the original code.

Munch is a dictionary that supports attribute-style access, a la JavaScript:

>>> from munch import Munch
>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True

Dictionary Methods

A Munch is a subclass of dict; it supports all the methods a dict does:

>>> list(b.keys())
['hello', 'foo']

Including update():

>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print(repr(b))
Munch({'hello': 42, 'foo': Munch({'lol': True}), 'ponies': 'are pretty!'})

As well as iteration:

>>> [ (k,b[k]) for k in b ]
[('hello', 42), ('foo', Munch({'lol': True})), ('ponies', 'are pretty!')]

And "splats":

>>> "The {knights} who say {ni}!".format(**Munch(knights='lolcats', ni='can haz'))
'The lolcats who say can haz!'

Serialization

Munches happily and transparently serialize to JSON and YAML.

>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> import json
>>> json.dumps(b)
'{"foo": {"lol": true}, "hello": 42, "ponies": "are pretty!"}'

If JSON support is present (json or simplejson), Munch will have a toJSON() method which returns the object as a JSON string.

If you have PyYAML installed, Munch attempts to register itself with the various YAML Representers so that Munches can be transparently dumped and loaded.

>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> import yaml
>>> yaml.dump(b)
'!munch.Munch\nfoo: !munch.Munch\n  lol: true\nhello: 42\nponies: are pretty!\n'
>>> yaml.safe_dump(b)
'foo:\n  lol: true\nhello: 42\nponies: are pretty!\n'

In addition, Munch instances will have a toYAML() method that returns the YAML string using yaml.safe_dump(). This method also replaces __str__ if present, as I find it far more readable. You can revert back to Python's default use of __repr__ with a simple assignment: Munch.__str__ = Munch.__repr__. The Munch class will also have a static method Munch.fromYAML(), which loads a Munch out of a YAML string.

Finally, Munch converts easily and recursively to (unmunchify(), Munch.toDict()) and from (munchify(), Munch.fromDict()) a normal dict, making it easy to cleanly serialize them in other formats.

Default Values

DefaultMunch instances return a specific default value when an attribute is missing from the collection. Like collections.defaultdict, the first argument is the value to use for missing keys:

>>> from munch import DefaultMunch
>>> undefined = object()
>>> b = DefaultMunch(undefined, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo is undefined
True

DefaultMunch.fromDict() also takes the default argument:

>>> undefined = object()
>>> b = DefaultMunch.fromDict({'recursively': {'nested': 'value'}}, undefined)
>>> b.recursively.nested == 'value'
True
>>> b.recursively.foo is undefined
True

Or you can use DefaultFactoryMunch to specify a factory for generating missing attributes. The first argument is the factory:

>>> from munch import DefaultFactoryMunch
>>> b = DefaultFactoryMunch(list, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo
[]
>>> b.bar.append('hello')
>>> b.bar
['hello']

Miscellaneous

  • It is safe to import * from this module. You'll get: Munch, DefaultMunch, DefaultFactoryMunch, munchify and unmunchify.
  • Ample Tests. Just run pip install tox && tox from the project root.

Feedback

Open a ticket / fork the project on GitHub.

munch's People

Contributors

atleta avatar bobh66 avatar c3aw avatar d1618033 avatar dhellmann avatar dsc avatar ewouth avatar femtotrader avatar grzn avatar innermatrix avatar jacobsvante avatar jamshedvesuna avatar josepvb avatar kbni avatar maormarcus avatar mboisson avatar mdornseif avatar pabelanger avatar vmalloc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

munch's Issues

Numpy Integration

Hi,

Ive been using Munch and i love it, but i am missing a Munch numpy implementation.
what i have been doing recently is checking recursively all munches related to possible lists. When it finds a list it gets converted to numpy.
This is quite helpful for me, idk if is there a method that i have missed, but it is something that could be useful to the repo as a flag, such as lists2numpy when creating the munch.

    def convert_YAML2Struct(self, yaml):
        data = DefaultMunch.fromDict(yaml)
        for name in dir(data):
            current_key = getattr(data, name)
            setattr(data, name, self.check_munch_key(current_key))
            setattr(self, name, getattr(data, name))

    def check_munch_key(self, current_key):
        for i in dir(current_key):
            if isinstance(getattr(current_key, i), list):
                setattr(current_key, i, np.array(getattr(current_key, i)))
            elif isinstance(getattr(current_key, i), munch.DefaultMunch):
                setattr(current_key, i, self.check_munch_key(getattr(current_key, i)))
        return current_key

Best Regards,
Yuri

Please publish python universal wheel

What are wheels?
Wheels are the new standard of Python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

Advantages of wheels
Faster installation for pure Python and native C extension packages.
Avoids arbitrary code execution for installation. (Avoids setup.py)
Installation of a C extension does not require a compiler on Windows or macOS.
Allows better caching for testing and continuous integration.
Creates .pyc files as part of installation to ensure they match the Python interpreter used.
More consistent installs across platforms and machines.

https://pythonwheels.com/

Must appreciated!

Python 3.13 adds new class attributes: __firstlineno__ and __static_attributes__, resulting in failing test_reserved_attributes

The tests fail with Python 3.13.0b1 with the traceback below.

per https://docs.python.org/dev/whatsnew/3.13.html:

  • __firstlineno__ is the line number of the first line of the class definition
  • __static_attributes__ is a tuple of names of attributes of this class which are accessed through self.X from any function in its body. For munch, the value is ('update', '__class__'), but I'm not entirely sure it's fixed.
=================================== FAILURES ===================================
__________________ test_reserved_attributes[__firstlineno__] ___________________

attrname = '__firstlineno__'

    @pytest.mark.parametrize("attrname", dir(Munch))
    def test_reserved_attributes(attrname):
        # Make sure that the default attributes on the Munch instance are
        # accessible.
    
        taken_munch = Munch(**{attrname: 'abc123'})
    
        # Make sure that the attribute is determined as in the filled collection...
        assert attrname in taken_munch
    
        # ...and that it is available using key access...
        assert taken_munch[attrname] == 'abc123'
    
        # ...but that it is not available using attribute access.
        attr = getattr(taken_munch, attrname)
        assert attr != 'abc123'
    
        empty_munch = Munch()
    
        # Make sure that the attribute is not seen contained in the empty
        # collection...
        assert attrname not in empty_munch
    
        # ...and that the attr is of the correct original type.
        attr = getattr(empty_munch, attrname)
        if attrname == '__doc__':
            assert isinstance(attr, str)
        elif attrname in ('__hash__', '__weakref__'):
            assert attr is None
        elif attrname == '__module__':
            assert attr == 'munch'
        elif attrname == '__dict__':
            assert attr == {}
        else:
>           assert callable(attr)
E           assert False
E            +  where False = callable(35)

tests/test_munch.py:229: AssertionError
_______________ test_reserved_attributes[__static_attributes__] ________________

attrname = '__static_attributes__'

    @pytest.mark.parametrize("attrname", dir(Munch))
    def test_reserved_attributes(attrname):
        # Make sure that the default attributes on the Munch instance are
        # accessible.
    
        taken_munch = Munch(**{attrname: 'abc123'})
    
        # Make sure that the attribute is determined as in the filled collection...
        assert attrname in taken_munch
    
        # ...and that it is available using key access...
        assert taken_munch[attrname] == 'abc123'
    
        # ...but that it is not available using attribute access.
        attr = getattr(taken_munch, attrname)
        assert attr != 'abc123'
    
        empty_munch = Munch()
    
        # Make sure that the attribute is not seen contained in the empty
        # collection...
        assert attrname not in empty_munch
    
        # ...and that the attr is of the correct original type.
        attr = getattr(empty_munch, attrname)
        if attrname == '__doc__':
            assert isinstance(attr, str)
        elif attrname in ('__hash__', '__weakref__'):
            assert attr is None
        elif attrname == '__module__':
            assert attr == 'munch'
        elif attrname == '__dict__':
            assert attr == {}
        else:
>           assert callable(attr)
E           AssertionError: assert False
E            +  where False = callable(('update', '__class__'))

tests/test_munch.py:229: AssertionError

version parsing

hello,
i installed munch on a server.
on that server, python packages are pre-built to suit the server architecture.
when installing the pre-built package, they add to its version an extension from the server name.
e.g. when install munch 2.5.0, the munch.__version__ will be 2.5.0+severx.
when importing munch, i get this this error that occurs when parsing the version in munch.__init__:

In [4]: import munch
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-e9b07ae78567> in <module>()
----> 1 import munch

~/Venvs/xxx/lib/python3.7/site-packages/munch/__init__.py in <module>()
     27 
     28 __version__ = pkg_resources.get_distribution('munch').version
---> 29 VERSION = tuple(map(int, __version__.split('.')[:3]))
     30 
     31 __all__ = ('Munch', 'munchify', 'DefaultMunch', 'DefaultFactoryMunch', 'unmunchify')

ValueError: invalid literal for int() with base 10: '0+serverx'

version:
Python 3.7.9 munch 2.5.0

any idea how to fix this?
thanks

mucnh does not seem to work when called using python's exec method

Hi:

Perhaps I am dong something wrong here - trying to execute a munch statement written as text using exec('text'). Does not seem to work. Per the attached yaml file, devices.GPIO18.type should be "door." When executed using exec it comes back as "None.":

print(devices.GPIO18.type)
print(exec('devices.GPIO18.type'))

yields:

%Run test.py

door
None

I've attached the yaml file and the code. Many thanks - Elliot
alarmDevices.txt
test.py.txt

OrderedMunch

Hello,

an OrderedMunch (similar to OrderedDict) will be a great data structure to have.

Kind regards

Munch Errors with IronPython

I was testing another python library in IronPython which calls munch, I found some errors when importing munch in IronPython. Here's what I did:

>>>import munch
Runtime error (ArgumentTypeException): unicode_escape_decode() takes no arguments (1 given)
Traceback:
  line 337, in <module>, "C:\Anaconda2\Lib\site-packages\munch\__init__.py"
  line 6, in script
  line 14, in u, "C:\Anaconda2\Lib\site-packages\munch\python3_compat.py"

I had consulted @dglassman for this issue, and here is his solution:
The conflicts are in python3_compat.py. "The issue is that munch includes a shim for compatibility with Python3, but IronPython doesn't understand it. And since we're working with Python 2.7, we don't need it."

The line 14 of the original python3_compat.py was:
return codecs.unicode_escape_decode(string)[0]

Is replaced with:
return unicode(string)

After I made this change, the munch library is imported successfully.

This might be a potential issue for IronPython users, if the solution is correct, please make the updates in next release.

Setup.py Update

I believe setup.py should be using install_requires instead of setup_requires. I ended up with a weird dependency issue that occurs for munch versions > 2.3.2.

Describe Installation / Link out to Pypi page

Authenticate the munch Pypi page as an official distribution by mentioning it / linking to it in the readme.

Another way to make the pypi namespace evident would be to add an Installation section that says pip install munch

This creates easy confidence that pip's 'munch' is this munch, reducing concerns as we worry more about the providence of our dependencies.

New Release

Hi, is it OK if we can have a new release tag?

We are using Munch in our system, and the copy method is missing from 2.0.4 which was released in 2015. It is easy to walk around it, but at this point, it's cleaner if we can have a new release tag.

Thanks in advance!

Support for pretty printing

Pretty printing a complex object does not really work...

from munch import munchify
from pprint import pprint

a = {
  "a": [1, 2, 3],
  "b": {
    "inner": {
      "inner-inner": [1, 2, 3],
      "inner-inner2": [1, 2, 3],
      "inner-inner3": [1, 2, 3],
    },
    "second-inner": "asdfasdf",
  },
  "c": {
    "inner": {
      "inner-inner": [1, 2, 3],
      "inner-inner2": [1, 2, 3],
      "inner-inner3": [1, 2, 3],
    },
    "second-inner": "asdfasdf",
  }
}
pprint(munchify(a))

Results in:

Munch("{'a': [1, 2, 3], 'c': {'second-inner': 'asdfasdf', 'inner': {'inner-inner': [1, 2, 3], 'inner-inner3': [1, 2, 3], 'inner-inner2': [1, 2, 3]}}, 'b': {'second-inner': 'asdfasdf', 'inner': {'inner-inner': [1, 2, 3], 'inner-inner3': [1, 2, 3], 'inner-inner2': [1, 2, 3]}}}")

Need exception thrown for missing attributes

Need a way to tell Munch to throw an exception (AttributeError or something) when an attribute is missing. Today, it returns None, or you can set a default value, but you can't configure it to throw an exception.

Why is this important?

Munchified dictionaries don't work with existing getattr() calls

Say you have existing code without munch that does this:

    foo = getattr(conf, 'foo', 1)

If conf['foo'] does not exist, foo gets set to 1

Now, lets say you munchify conf (so that you can easily access the fields). This will break existing getattrs. Using the same code:

    from munch import DefaultMunch

    conf = DefaultMunch.fromDict(conf)        
    foo = getattr(conf, 'foo', 1)

Now, id conf['foo'] does not exist, BUT foo gets set to None. This breaks any existing code that was using getattr(). getattr() is a very commonly used for dict access and specifying default values.

We need a way to use the ease of accessing fields, but still throw an exception on missing attributes

Deserializing a munchified object makes it an dict

I am trying to create an Munch object and when I serialize it to JSON and deserialize it, I am getting an dict, rather than an object.

a = Munch(status_code= 200, text= {'code': '1234'})

a.status_code # result 200

a_js=json.dumps(a)

json.loads(a_js).status_code # AttributeError: 'dict' object has no attribute 'status_code'

munchify/unmunchify fail if they encounter cycles

from munch import munchify

x = dict()
y = dict(x=x)
x['y']=y
munchify(x)

→ RecursionError

from munch import Munch, unmunchify

x = Munch()
y = Munch(y=x)
x['y'] = y

unmunchify(x)

→ RecursionError

DefaultMunch TypeError

The defaultdict example from its documentation produces TypeError

from munch import DefaultMunch
#from collections import defaultdict

import sys;     print(sys.version)
import munch;   print(munch.__version__)

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
#d = defaultdict(list)
d = DefaultMunch(list)
for k, v in s: d[k].append(v)

print(sorted(d.items()))

outputs

3.8.5 (default, Jul 28 2020, 12:59:40)
[GCC 9.3.0]
2.3.2
Traceback (most recent call last):
  File "test_DefaultMunch.py", line 10, in <module>
    for k, v in s: d[k].append(v)
TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' object

DefaultMunch version release

Hello,

This is not an issue but a question. When is the DefaultMunch/munchify with a factory going to be released? Because I really need those 2 options

Recursive dict merge

Thanks for creating this useful package.

Could you add a merge(self, other_munch_obj/mapping_obj) function to merge them recursively.

Thanks in advance.
Jason.

Immutable/frozen munch

Hi, I am searching a best type for config data, usually it is nested dict, but on my opinion config must:

  1. have dot notation for readability,
  2. be immutable for safe using (config is global variable).
    Can Munch be immutable?

P.S. I found https://github.com/cdgriffith/Box/ but not sure that it popular = good tested.

New release

Hi, there are some new useful features since last release. Is it possible to provide the new one?

What are the recommended type annotations?

Suppose I have this:

from munch import munchify


def gen_dict():
    return munchify({'foo': 'bar', 'id': 123})    

What is the recommended way to type annotate the return value of gen_dict()? Simply munch.Munch?

Undeclared dependency on setuptools (pkg_resources)

On a system without Setuptools pre-installed, munch fails on import:

~ $ pip-run munch -- -c "import munch"
Collecting munch
  Using cached munch-2.5.0-py2.py3-none-any.whl (10 kB)
Collecting six
  Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
Installing collected packages: six, munch
Successfully installed munch-2.5.0 six-1.15.0
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/var/folders/c6/v7hnmq453xb6p2dbz1gqc6rr0000gn/T/pip-run-y4m51iwb/munch/__init__.py", line 24, in <module>
    import pkg_resources
ModuleNotFoundError: No module named 'pkg_resources'

The project should remove use of pkg_resources or declare the dependency on setuptools.

support recursive munching

from munch import Munch

d = {'hello_world': {'cooldown': 30,
                 'items_per_replica': 3,
                 'replicas': {'max': 6, 'min': 3}},
 }
m = Munch(d)
m.hello_world.replicas.min
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    m.hello_world.replicas.min
AttributeError: 'dict' object has no attribute 'replicas'

Something is wrong with munch and pickle

An easy test case that shows something is wrong here.

>>> m = {'a': {'b': 'c'}}
>>> m = munch.munchify(m)
>>> m
Munch({'a': Munch({'b': 'c'})})
>>> e = munch.munchify(m)
>>> pickle.loads(pickle.dumps(e))
Munch({'a': {'b': 'c'}})

I did not expect to lose information when using pickle; but it appears it does.

Key with Python reserved names like "for"

I have an dictionary which i like to convert to a Munch. The problem is, that my dictionary has a key named "for" which results in a Munch.for attrubite, which is not callable because "for" is a reserved keyword of Python.
What do you think about manipulating the dictionary keys inside the Munch class so that they can not be one of the Python keywords which you can get by keyword.kwlist.

Instead altering those dictionary keys to _for, _else etc.
I know this is a very specific problem and you can workaround this by calling Munch.get("for") but i think it is super weird to generate those attributes in the first place.

For some background:
Im getting a dictionary from the streamlabs API

{
  "type": "follow",
  "message": [
    {
      "created_at": "2017-08-22 00:14:35",
      "id": "170884026",
      "name": "h4r5h48002",
      "_id": "74a0b93e736f1f14762111f8ae34bf42"
    }
  ],
  "for": "twitch_account"
}

There is no __dict__ attribute on an object that inherits from Munch

If I define an object that inherits from Munch:

class Foo(Munch):
def init(self, bar):
self.bar = bar

and then do:

myfoo = Foo("mybar")

the resulting myfoo object has no dict attribute, so while I can do myfoo.toDict(), I can't do myfoo.dict which would be nice to allow it to be treated like any other object.

@Property
def dict(self):
return self.toDict()

would allow myfoo.dict to work the same way as toDict()

DefaultMunch.fromYAML should take default argument

Currently, DefaultMunch.fromYAML is the same as Munch.fromYAML. This is confusing, and it is a pitty because a real DefaultMunch.fromYAML would add functionality which, FWIW, I could use. Thus, I propose to create a dedicated DefaultMunch.fromYAML function with a parameter for the default value.

Cannot import Munch if the wheel doesn't come from a regular source

Hi !
Munch is a dependancy in a project of mine. When loaded in an env. where the wheels are locally provided, it cannot be imported properly as we see in the following traceback:

Traceback (most recent call last):
File "/home/script.py", line 7, in
import munch
File "/localscratch/temp_instance/env/lib/python3.8/site-packages/munch/init.py", line 29, in
VERSION = tuple(map(int, version.split('.')[:3]))
ValueError: invalid literal for int() with base 10: '0+computecanada'

TypeError: multiple bases have instance lay-out conflict

Many thanks for Much – it's used literally everywhere in https://github.com/PennyDreadfulMTG/Penny-Dreadful-Tools

I'm using Munch in multiple inheritance and getting this error when using it alongside the latest version (only) of anytree's NodeMixin. This seems more like an anytree issue (NodeMixin is meant to be mixed in, hence the name) but I thought I'd ask here also in case it makes any sense to a Munch dev.

>>> from munch import Munch
>>> from anytree import NodeMixin
>>> class MyClass(Munch, NodeMixin):
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: multiple bases have instance lay-out conflict

Where anytree is https://github.com/c0fec0de/anytree

Googling around a bit this seems to be about conflicts in C implementations of classes on __foo__ attributes. Do you understand what is going on here and/or how I can fix? Thanks!

See also:

c0fec0de/anytree#77
PennyDreadfulMTG/Penny-Dreadful-Tools#6072

Munch cannot recursively fetch values beyond first level when passed with a dot notation.

I am trying to read a config file in JSON and fetch values using Munch object notation. I am able to fetch first level keys using d['region'] and it returns {'api_key': 'abcdefgh'} but when I query d['region.api_key'], DefaultMunch returns None.

Expected behaviour: d['region.api_key'] returns 'abcdefgh'.

Can Munch recursively fetch values? Please advise.

I am using Munch from PyPi, v2.5.0

config.json

 { 'name': 'test', 'region': {'api_key': 'abcdefgh'}}

main.py

def get_config_from_file(config_key):

    f = open('config.json', 'r+')
    json_object = json.loads(f.read())

    if "." in config_key: # for example, config_key is 'region.api_key', then Munch!
        d = DefaultMunch.fromDict(json_object)
        print("Munch: " + str(d[config_key]))
        return d[config_key]

    elif json_object[config_key]: # for example, config key is a simple 'name', then access Dict normally
        return str(json_object[config_key])
    return ""`

if __name__ == "__main__":
    get_config_from_file('region.api_key')

Adding list support

Hi, is there any way to make this code actually work with Munch ? i.e recursively converting dictionaries inside lists

from munch import Munch

# Create a nested dictionary with lists containing dictionaries
nested_dict = {
    "a": [{"b": 1, "c": 2}, {"d": 3, "e": 4}],
    "f": {"g": [{"h": 5}, {"i": 6}]}
}

# Convert the dictionary to a Munch object
munch_obj = Munch(nested_dict)

# Access nested dictionaries in the list using dot notation and indexing
print(munch_obj.a[0].b)  # Output: 1
print(munch_obj.a[1].e)  # Output: 4
print(munch_obj.f.g[1].i)  # Output: 6

The easiest way to do this is just

def convert_to_munch(data):
    if isinstance(data, dict):
        return Munch({k: convert_to_munch(v) for k, v in data.items()})
    elif isinstance(data, list):
        return [convert_to_munch(item) for item in data]
    else:
        return data

but it would be cool if this just work out of the box I think

Problem calling attributes containing '-'

Hello,

I have been using the Munch library for a while now.
On my python code, I imported some parametrs from an YAML file and then tried to iterate on them one by one. The problem is that some parametrs with the '-' caracter are not accepted and my python 3.11.7 throws :

Traceback (most recent call last):
  File "PATH\venv\Lib\site-packages\munch\__init__.py", line 116, in __getattr__
    return object.__getattribute__(self, k)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Munch' object has no attribute 'llm'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "PATH\venv\Lib\site-packages\munch\__init__.py", line 119, in __getattr__
    return self[k]
KeyError: 'llm'

My key is llm-api but the Munch object does just recongnize llm and not the rest of the key.
Is this a common problem?

PS : I resolved this issue by replacing '-' to '_' on my YAML file and it works perfectly, otherways I just want to report this because it made me crazy for some hours and also to help some beautiful lost soul in the future.

munchify broken?

Here is a minimal working example, which is broken. Is this already fixed?

munchify((1,2,[{'A': 'B'}])) Result: (1, 2, [Munch({'A': 'B'}), Munch({'A': 'B'})]) Expected: (1, 2, [Munch({'A': 'B'})])

is Munch thread safe for reading?

We are using munch for a service hosted in IIS. Due to the large size of the data (17GB) in munch, only one python instance can be created through Flask under IIS. Now the question is, would the munch support multiple calls almost simultaneously from different users through Flask APIs without the worry on thread race.

_make is part of namedtuple's contract, not tuple

I think these should read namedtuple:

https://github.com/Infinidat/munch/blob/d0aeb06/munch/__init__.py#L461
https://github.com/Infinidat/munch/blob/d0aeb06/munch/__init__.py#L523

Currently, if a custom class inherits from tuple and an instance ends up with a _make attribute, munch will call it when the __dict__ attribute is accessed. Unlikely to happen by chance, but munch also inserts itself into SafeLoader, so it should probably err on the defensive side.

DefaultMunch getter now returns None instead of DefaultValue

If a DefaultMunch has a default value of None, munch.get(attr_name, default_value) will now return None instead of default_value

>>> from munch import DefaultMunch
>>> d = DefaultMunch(None, {'a': 1})
>>> d.get('a')
1
>>> d.get('b')
>>> d.get('b', 'test')
>>> d.get('b', 'test') is None
True

This is a devastating change in behavior from the previous version:

>>> from munch import DefaultMunch
>>> d = DefaultMunch(None, {'a': 1})
>>> d.get('a')
1
>>> d.get('b')
>>> d.get('b', 'test')
'test'
>>> d.get('b', 'test') is None
False

munch.fromYAML issue

In munch version 2.5.0 the funcation fromYAML requires as a first argument cls. This is not documented. What is it? Reference to some class?
Can you please give an example?

Thanks for this useful tool!

Accessing serialized json with numeric string as keys

hi
Consider the following case:

from munch import munchify

INFO = munchify({
        "1234": {
            "first_name": "munch",
            "last_name": "munchi"
        }})

INFO.1234

You get as a result:

File "<stdin>", line 1
    INFO.1234
                    ^
SyntaxError: invalid syntax

Is there any intention to support numeric values?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.