#### 4.3.1 Enhanced Robj

This example shows an extended `Robj` type which supports R attribute look up via normal Python attribute access. It also supports the representation given by the R interpreter, and it implements the `as_r()` method for converting itself to R.

In Python 2.2 you can take advantage of the possibility to subclass types, and the examples can be rewritten in a more powerful way. However, these examples are Python 2.1 and 2.2 compatible.

File `erobj.py`:

    from rpy import *

    class ERobj:

        def __init__(self, robj):
            self.robj = robj

        def as_r(self):
            return self.robj

        def __str__(self):
            a = with_mode(NO_CONVERSION,
                          lambda: r.textConnection('tmpobj', 'w'))()
            r.sink(file=a, type='output')
            r.print_(self.robj)
            r.sink()
            r.close_connection(a)
            str = with_mode(BASIC_CONVERSION,
                            lambda: r('tmpobj'))()
            return '\n'.join(as_list(str))

        def __getattr__(self, attr):
            e = with_mode(BASIC_CONVERSION,
                          lambda: r['$'](self.robj, attr))()
            if e:
                return e
            return self.__dict__[attr]

The `__str__` method makes the R interpreter print to the `tmpobj` R variable. Then, it is retrieved and returned as the string representation of the object. Note the use of the `with_mode` function for not changing the mode in use. Note, also, the use of the utility functions `as_list` and `r` (see Miscellaneous).

An example of use:

    >>> from rpy import *
    >>> from erobj import *
    >>> proc_table[lambda o: 1] = ERobj
    >>> set_default_mode(PROC_CONVERSION)
    >>>
    >>> e = r.t_test([1,2,3])
    >>> e
    <erobj.ERobj instance at 0x8ad4ea4>
    >>> print e

            One Sample t-test

    data:  c(1, 2, 3)
    t = 3.4641, df = 2, p-value = 0.07418
    alternative hypothesis: true mean is not equal to 0
    95 percent confidence interval:
     -0.4841377  4.4841377
    sample estimates:
    mean of x
            2

    >>>
    >>> e.statistic
    {'t': 3.4641016151377548}