Welcome, guest | Sign In | My Account | Store | Cart

Enriches (return) values transparently with extra data.

Python, 33 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Enriches (return) values transparently with extra data.

def RICHVALUE(v, **kwargs):
    try:
        class _RICHVALUE(type(v)):
            pass
        vv=_RICHVALUE(v)
    except TypeError:
        import copy
        vv=copy.copy(v)
    vv.__dict__.update(kwargs)
    return vv

def f():
    return RICHVALUE(7, extra="hello")

def g():
    class X: pass
    return RICHVALUE(X(), extra="hello")

def h(want_extra=False):
    class Y(object): pass
    y=Y()
    if want_extra:
        return RICHVALUE(y, extra="hello")
    return y

ret=f()
print ret, ret+1, ret.extra
ret=g()
print ret, ret.extra
ret=h(want_extra=True)
print ret, getattr(ret,'extra',"???")

While evolving code, there is often a need to enrich an existing simple return scheme of a function by extra/optional return values. Using (variable lenght) return tuples often introduces puzzles - and the pychecker yells. In such cases the RICHVALUE recipe offers a transparent method for adding extra return values.

Drawbacks: Pickling exceptions, if such enriched values (builtin types) are pickled without typecasting.

Created by R K on Fri, 5 May 2006 (PSF)
Python recipes (4591)
R K's recipes (5)

Required Modules

Other Information and Tasks