Storing value with limits in object

David wizzardx at gmail.com
Sun Jun 22 07:11:01 EDT 2008


On Sun, Jun 22, 2008 at 12:24 PM, Josip <fake.mail at noone.be> wrote:
>> Not with normal vars, because = is a rebinding operator in Python,
>> rather than assignment.
>>
>> You can do (close to) the above with object properties.
>>
>> David.
>
> Yes, but it's done with built-in types like int and float. I suspect I could
> subclass from them and implement limits, but I would have to make
> seperate class for each type. Can I override conversion methods like int()
> and float() within my class?
>

I think I may have misread your original post.

ints and floats are internal , immutable types, with some class
goodness on top (so you can treat them like objects to a degree,
subclass from them, etc). Python's interpreter has built-in logic
which 'knows' how to use ints and floats variables, without calling
their special "__" methods. Python would be a lot slower if it worked
this way.

To do exactly what you want, you'd need to add a new internal numeric
type to Python.

You can subclass from float, and redefine __float__ and __int__, but
those will only be called when your code actually calls the builtin
float() and int() builtins, eg:

import math

class Float(float):
    def __float__(self):
        raise NotImplementedError

a = Float(1)
print math.sin(a)

# Outputs 0.841470984808

a = Float(1)
print math.sin(float(a))

# Throws a NotImplementedError exception

There is no way (afaik) for an object to tell Python to call one of
it's methods to get a reference, or 'value' to the object (if there
was, it would make things really complicated). In Python you generally
need to update the logic used during a lookup to get that effect (ie,
in  a.b.c, you can customise the a.b lookup, or the a.b.c lookup, but
not the a lookup itself).

In theory you could hack Python's internal locals or globals
dictionary so that it did something unusual while looking up your
object. But in practice this doesn't work, because the returned
objects (when you call globals() or locals()) attributes are readonly.
Probably because those internal lookup dicts are implemented in
optimized C not Python, and the C implementation doesn't let you
redefine it's internals via the Python interface.

David.



More information about the Python-list mailing list