dsc / bunch Goto Github PK
View Code? Open in Web Editor NEWA Bunch is a Python dictionary that provides attribute-style access (a la JavaScript objects).
Home Page: http://github.com/dsc/bunch
License: MIT License
A Bunch is a Python dictionary that provides attribute-style access (a la JavaScript objects).
Home Page: http://github.com/dsc/bunch
License: MIT License
Hello,
I did this
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flufl.enum import Enum
from bunch import Bunch
class MyEnum(Enum):
VAL1 = 1
VAL2 = 2
VAL3 = 3
b = Bunch()
b.x = 1
b.e = MyEnum.VAL1
print(b)
It raises
Traceback (most recent call last):
File "bug_bunch_enum.py", line 16, in <module>
print(b)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bunch/__init__.py", line 384, in toYAML
return yaml.safe_dump(self, **opts)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/__init__.py", line 218, in safe_dump
return dump_all([data], stream, Dumper=SafeDumper, **kwds)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/__init__.py", line 190, in dump_all
dumper.represent(data)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/representer.py", line 28, in represent
node = self.represent_data(data)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/representer.py", line 57, in represent_data
node = self.yaml_representers[data_types[0]](self, data)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bunch/__init__.py", line 342, in to_yaml_safe
return dumper.represent_dict(data)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/representer.py", line 223, in represent_dict
return self.represent_mapping(u'tag:yaml.org,2002:map', data)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/representer.py", line 123, in represent_mapping
node_value = self.represent_data(item_value)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/representer.py", line 67, in represent_data
node = self.yaml_representers[None](self, data)
File "/Users/scls/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/yaml/representer.py", line 247, in represent_undefined
raise RepresenterError("cannot represent an object: %s" % data)
yaml.representer.RepresenterError: cannot represent an object: MyEnum.VAL1
Any idea how to fix this ?
Kind regards
Sébastien
If PyYAML is installed (even if unwittingly by the user), the following code crashes, for instance:
from uuid import uuid1
b = Bunch(id=uuid1())
str(b)
This breaks a lot of cases using Bunch for data container, rather than a YAML/json intermediate format...
Hello,
I wonder how to pretty print Bunch objects:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(b)
Any idea ?
My friend thanks for this amazing library , but please would be possible add support to python 3.
I think that is only change iteritems by items() , return Bunch( (k, bunchify(v)) for k,v in items(x) ) .
thanks
Hi @vmalloc
see this Travis build https://travis-ci.org/ig-python/ig-markets-api-python-library/jobs/83294568
(using Python 3)
from infi.bunch import bunchify
File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/infi/bunch/__init__.py", line 31, in <module>
from .python3_compat import *
File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/infi/bunch/python3_compat.py", line 20, in <module>
iteritems = dict.iteritems
AttributeError: type object 'dict' has no attribute 'iteritems'
Any idea ?
I think your python3_compat.py
is wrong and Python 3 is recognized as Python 2.
Kind regards
Hello,
I think it will be nice to add some tests (not with unittest
package but using either nosetests
or py.test
Moreover continuous integration with Travis-CI will be a good idea
it will probably help to ensure Python 3 transition without regression on Python 2
Kind regards
In the file python3_compat.py this line:
_IS_PYTHON_3 = (platform.version() >= '3')
is not a sufficient method for determing if python 3 is being used. For example on my machine this returns #86-Ubuntu SMP Mon May 4 04:32:59 UTC 2015
and I'm running python 3.4.
Ideally we should use something like 2to3, but we might be able to use sys.version.
I took most recent fork
https://github.com/redodo/lunch/
and fork it https://github.com/femtotrader/lunch/
to add CI
https://travis-ci.org/femtotrader/lunch
I saw this with Python 3.3:
AttributeError: 'Bunch' object attribute 'values' is read-only
Any idea ?
0.11s$ python tests/test_bunch.py
File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/bunch/init.py", line 163, in bunch.Bunch.delattr
Failed example:
del b.values
Expected:
Traceback (most recent call last):
...
AttributeError: 'Bunch' object attribute 'values' is read-only
Got:
Traceback (most recent call last):
File "/opt/python/3.3.5/lib/python3.3/doctest.py", line 1313, in run
compileflags, 1), test.globs)
File "<doctest bunch.Bunch.__delattr[1]>", line 1, in
del b.values
File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/bunch/init.py", line 182, in delattr
object.delattr(self, k)
AttributeError: values
1 items had failures:
1 of 4 in bunch.Bunch.delattr
_Test Failed_ 1 failures.
The command "python tests/test_bunch.py" exited with 1.
I liked AttrDict. Then AttrDict was too slow. I liked Bunch. Then Bunch was too slow. These two libraries ended up consuming 1/2 and 1/3 of my request time when using them frequently, for what I had assumed was a very simple use-case. The main problem comes from two things 1) Bunch inherits from dict
, so it brings along the entire dict
implementation, which isn't always necessary(rarely is in fact). 2)bunchify
aggressively goes through an entire nested dictionary, and puts copies of Bunch everywhere. This results in attributes that may never get called, getting implanted with the Bunch object.
Speeding this up proved to not take a lot of code. Check out this gist from @mmerickel, which I've copied below. It uses a light-weight DictProxy object to mediate access to the object, and it also lazy-loads each attribute. This decreased the amount of time that my app spend "Bunching" objects to relatively nothing, from 1/3 of my request time using Bunch master.
class DictProxy(object):
"""
A proxy for a dictionary that allows attribute access to underlying keys.
You may pass a custom ``wrapper`` to override the logic for wrapping
various custom types.
"""
def __init__(self, obj, wrapper=wrap):
self.obj = obj
def __getitem__(self, key):
return self.wrapper(self.obj[key])
def __getattr__(self, key):
try:
return self.wrapper(getattr(self.obj, key))
except AttributeError:
try:
return self[key]
except KeyError:
raise AttributeError(key)
# you probably also want to proxy important list properties along like
# items(), iteritems() and __len__
class ListProxy(object):
"""
A proxy for a list that allows for wrapping items.
You may pass a custom ``wrapper`` to override the logic for wrapping
various custom types.
"""
def __init__(self, obj, wrapper=wrap):
self.obj = obj
def __getitem__(self, key):
return self.wrapper(self.obj[key])
# you probably also want to proxy important list properties along like
# __iter__ and __len__
def wrap(value):
"""
The top-level API for wrapping an arbitrary object.
This only works for ``dict``, ``list`` and ``tuple`` types. If you want
to wrap other types you may write your own wrap and pass ``wrapper=`` to
``DictProxy`` and ``ListProxy``.
"""
if isinstance(value, dict):
return DictProxy(value)
if isinstance(value, (tuple, list)):
return ListProxy(value)
return value
Things look a bit strange at:
https://github.com/dsc/bunch/blob/master/bunch/__init__.py#L286-L290
I think the imports should be the other way around:
simplejson as json
json
, which should be available on your Python install.Hello,
With Python 2.7:
from bunch import Bunch
b=Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')
[ (k,b[k]) for k in b ]
returns
[('ponies', 'are pretty!'), ('foo', Bunch(lol=True)), ('hello', 42)]
but with Python 3.3
[ (k,b[k]) for k in b ]
returns
[('foo', Bunch(lol=True)), ('hello', 42), ('ponies', 'are pretty!')]
So some tests are failing.
Hello,
I try this fork of Bunch which seems interesting
https://github.com/Infinidat/munch
but Doctests don't run (never failed)
For example I changed:
>>> [ (k,b[k]) for k in b ]
[('ponies', 'are pretty!'), ('foo', Munch(lol=True)), ('hello', 42)]
to
>>> [ (k,b[k]) for k in b ]
[('ponies', 'are prettyERROR!'), ('foo', Munch(lol=True)), ('hello', 42)]
and no error raised (which is a problem as it should raise an error)
Hello,
it will be nice if Bunch
could recursively build a bunch of bunch from dict of dict.
Example:
from bunch import Bunch
old_bunch = Bunch({"a": 0, "b": {"b1": 1, "b2": 2}})
returns
Bunch(a=0, b={"b1": 1, "b2": 2})
it will be nice if it could returns
new_bunch = Bunch(a=0, b=Bunch(b1=1, b2=2))
Because accessing b2 sub key can be done using:
old_bunch.b["b2"]
recursively contructed Bunch could give access to b2 sub key using:
new_bunch.b.b2
Kind regards
I'm suspecting that the coverage for python 2 (which I use as CircuitPython) is broken. the 'if' and 'else' should be swapped:
Line 16 in 34eedf5
because in Python 2, you can't say
iteritems = dict.iteritems
iterkeys = dict.iterkeys
as dict doesn't include them
... except if we merge !
see https://github.com/dsc/bunch/network
Maybe we should create an organization and try to consolidate our efforts
I want to use Sourcegraph code search and code review with bunch. A project maintainer needs to enable it to set up a webhook so the code is up-to-date there.
Could you please enable bunch on @sourcegraph by going to https://sourcegraph.com/github.com/dsc/bunch and clicking on Settings? (It should only take 15 seconds.)
Thank you!
Sometimes is useful to keep parsing a large json object even when some properties are not present right now any key that's not found rises an error. My suggestion is that we could have an optional init parameter to define if we want strict rules or just returning None in case the key is not present.
Does this Bunch
implementation support Python 3?
I get some test errors with Python 3.4:
https://gist.github.com/cdeil/5525c1ee193f1426ee8b
And Python 3 support is not listed via the setup.py
classifiers:
https://pypi.python.org/pypi/bunch/
If it doesn't support Python 3, could you please state this in the README?
Test using dictionary:
>>> d={} >>> d[u'r\xf6k']="smoke" >>> u'r\xf6k' in d True >>> print repr(d) {u'r\xf6k': 'smoke'}
Test using bunch:
>>> b=Bunch() >>> b[u'r\xf6k']="smoke" >>> u'r\xf6k' in b False >>> print repr(b) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 7: ordinal not in range(128)
in setup.py line 11:
package_file = open(join(HERE, 'bunch/__init__.py'), 'rU')
"U" option for universal newline is no longer supported in python 3.11
It is not documented what happens if Bunch() is expanded using dictionary notation with an element, which key is invalid for property access?
Hello,
I see 2 README files
so the question is Markdown or reStructuredText ?
If you prefere Markdown you might be interested by
https://pypi.python.org/pypi/setuptools-markdown
Kind regards
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.