UserInt module and class

pmaupin at speakeasy.net pmaupin at speakeasy.net
Mon Oct 13 19:02:04 EDT 2003


Recently I found out the hard way that __coerce__
is not automatically called for new classes.

This means that, at least for me, a 'UserInt' module
is eminently useful, for objects which can be used
in expressions where a numeric result is desired.

Googling for 'python UserInt', I found a few close
things, some far-away things, and a
 "next-up-UserInt-ly y'rs  - tim" from 1998 when he
was describing why there was no UserString class :)

It occurred to me that others might want UserFloat,
etc. for similar reasons, so I wrote a meta-module
to generate the UserInt module.  Perhaps someone
will find it useful.

Best regards,
Patrick Maupin


print """
\"""A more or less complete user-defined wrapper around integer objects.\"""

class UserInt(object):
    def __int__(self):  raise TypeError, "This is a virtual class"
"""

unwanted_methods = dir(object)+['__int__','__getnewargs__']
methods = [i for i in dir(int) if i not in unwanted_methods]
methods.sort()

for i in methods:
    try: getattr(1,i)(1)
    except TypeError: params = (i,'',i,'')
    else: params = (i,',other',i,'int(other)')
    print '    def %s(self%s): return int(self).%s(%s)' % params








More information about the Python-list mailing list