Keep object extended from dict/list intact
See original GitHub issueHi @cdgriffith,
I am the one who proposed ordered_box
.
I was recently bothered by Box
turning some objects that are inherited from dict/list
into Box/BoxList
.
Consider the following codes:
from box import Box
class MyList(list):
def sq(self):
return [x*x for x in self]
b = Box(a = MyList([1,2,4]))
b.a.sq()
# AttributeError: 'BoxList' object has no attribute 'sq'
# Expect [1,4,16]
I extended list
to add some extra methods for convenience. However, when it was changed by Box
into a BoxList
, then I lost my method sq
.
Is it possible to keep the objects of extended dict/list
intact, but convert the raw dict/list
s?
One simple way is to check the __bases__
, if it is (object, )
then it should be a raw dict/list
:
def _israwinstance(obj, klass):
return isinstance(obj, klass) and obj.__class__.__bases__ \
and obj.__class__.__bases__[0] is object
Thanks, Panwen
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (5 by maintainers)
Top Results From Across the Web
Convert Django Model object to dict with all of the fields intact
To do this, we can use a loop that makes a new dictionary that has every item except those with underscores in them....
Read more >Python List Append VS Python List Extend – The Difference ...
extend () method. Each character of the string is considered an "item", so the characters are appended one by one in the order...
Read more >5. Data Structures — Python 3.11.1 documentation
Here are all of the methods of list objects: list.append(x) ... list.extend(iterable). Extend the list by appending all the items from the iterable....
Read more >Object Relationships Overview - Salesforce Help
Behaviors of master-detail relationships: Deleting a detail record moves it to the Recycle Bin and leaves the master record intact; deleting a master...
Read more >4. Methods Use Instance Variables: How Objects Behave
We know that objects have state and behavior, represented by instance variables and methods. But until now, we haven't looked at how state...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I understood your concern about not converting those subclasses of
dict
in this way, for example,OrderedDict
.What about we enabling a
kwarg
setting, saybox_intact_types
, to put those types, and excluding them in__convert_and_store
? My case would be then:In
__convert_and_store
while checking types, we could do:Version 3.4.0 released https://github.com/cdgriffith/Box/commit/5f09df824022127e7e335e3d993f7ddc1ed97fce