Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Python there are many ways of making objects behave slightly differently, like metaclasses and whatnot, and it can override <strong>getattr</strong> and thereby have "magical" attributes you can't see through <strong>dict</strong>, etc. In short, it's unlikely that you are going to get a 100% complete picture in the generic case with whatever method you use.</p> <p>Therefore, the answer is: If it works for you in the use case you have now, then the code is correct. ;-)</p> <p>To make somewhat more generic code you could do something like this:</p> <pre><code>import types def todict(obj): # Functions, methods and None have no further info of interest. if obj is None or isinstance(subobj, (types.FunctionType, types.MethodType)) return obj try: # If it's an iterable, return all the contents return [todict(x) for x in iter(obj)] except TypeError: pass try: # If it's a dictionary, recurse over it: result = {} for key in obj: result[key] = todict(obj) return result except TypeError: pass # It's neither a list nor a dict, so it's a normal object. # Get everything from dir and __dict__. That should be most things we can get hold of. attrs = set(dir(obj)) try: attrs.update(obj.__dict__.keys()) except AttributeError: pass result = {} for attr in attrs: result[attr] = todict(getattr(obj, attr, None)) return result </code></pre> <p>Something like that. That code is untested, though. This still doesn't cover the case when you override <strong>getattr</strong>, and I'm sure there are many more cases that it doens't cover and may not be coverable. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload