A couple of OOPython questions
David C. Fox
davidcfox at post.harvard.edu
Tue Sep 9 13:55:38 EDT 2003
Alexy Khrabrov wrote:
> OK, now I go to my python prompt and I want to inspect my objects as
> returned by the CORBA server. One of them represents an atom site. I
> merrily type just its name to see the great unknown unwrap before my
> eyes. Here:
>
>
>>>>a
>
> <MMS.StructConf instance at 0x8cb1b44>
>
> Hmm. That's not what I hoped for. Some fragments of code I saw run
> through my mind and I type in,
>
>
>>>>dir(a)
>
> ['_NP_RepositoryId', '__doc__', '__init__', '__module__', 'beg_auth',
> 'beg_label', 'conf_type', 'details', 'end_auth', 'end_label', 'id']
>
> Good, we're getting somewhere. I also googled out vars(a), which
> seems to be the same as a.__dict__ (are they?... why is __dict__ not
> shown above then? 2.2...)
>
> Printing out gazillion fields by hand for each class is silly, they
> only wrap strings and numbers and other objects of that nature. I am
> ready to dive in a recursive descent. No such luck -- whoever created
> CORBA bindings for python didn't make those objects dictionary-like!
> I can't get members by name, although they _are_ in some __dict__,
> useless apparently, until I supply __getitem__!
>
> Is there an easy way to write something _once_, general enough, to
> print out a hierarchy of nested objects which just don't have
> __getitem__, although every field is either a string or a number or
> another object?
I'm not sure exactly what you are looking for, but here's a first
attempt. Save the following to a Python file called recursive_repr,
import recursive_repr, and try print recursive_repr.pr(x).
import types
def type_or_class(x):
"""returns the type of a variable x, or its class when the latter is
more specific, so that the types of two variables can be compared
"""
t = type(x)
if t is types.InstanceType:
# for old-style classes, __class__ is more specific
return x.__class__
# for built-in types and new-style classes
return t
def name_of_class(x):
t = type_or_class(x)
return "%s.%s" % (t.__module__, t.__name__)
def pr(x):
if hasattr(x, '__dict__'):
# return "class %s: %s" % (name_of_class(x), pr(x.__dict__))
return {'class %s' % name_of_class(x) : pr(x.__dict__)}
elif type(x) is type({}):
d = {}
for key, value in x.items():
d[key] = pr(value)
# return repr(d)
return d
return x
>
> Cheers,
> Alexy Khrabrov
More information about the Python-list
mailing list