Giter Club home page Giter Club logo

bunch's People

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

bunch's Issues

Bunch of bunch from dict of dict

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

Unit tests and continuous integration

Hello,

I think it will be nice to add some tests (not with unittest package but using either nosetestsor 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

infi.bunch package raises AttributeError: type object 'dict' has no attribute 'iteritems'

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

Iteration order is different with py2 and py3

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.

Pretty print

Hello,

I wonder how to pretty print Bunch objects:

import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(b)

Any idea ?

Python 3 testing should be not

I'm suspecting that the coverage for python 2 (which I use as CircuitPython) is broken. the 'if' and 'else' should be swapped:

if _IS_PYTHON_3:

because in Python 2, you can't say
iteritems = dict.iteritems
iterkeys = dict.iterkeys

as dict doesn't include them

AttributeError: 'Bunch' object attribute 'values' is read-only

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.

Bunch is Slow

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

Bunch can't be displayed when flufl.enum is used

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

platform.version() not suitable for determining if using python 3

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.

Change raise AttributeError(k) to None

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.

Add support to python 3

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

Bunch is completely broken when using unicode strings

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)

Doctests in Munch fork don't run correctly

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)

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.