references/pointers in Python?

Ignacio Vazquez-Abrams ignacio at openservices.net
Wed Sep 12 13:22:25 EDT 2001


On Wed, 12 Sep 2001, Anton Lavrik wrote:

> On Wed, Sep 12, 2001 at 12:28:31PM -0400, Ignacio Vazquez-Abrams wrote:
> > You can do something like the following:
> >
> > ---
> > class MyVal:
> >   def __init__(self, val):
> >     self.set(val)
> >   def set(self, val):
> >     self.value=val
> >   def __call__(self):
> >     return self.value
> >
> > a=MyVal(5)
> > b=a
> > b.set(3)
> > print a()
> > ---
>
> Is this the only way? Actualy, I expect some perfomace when operating
> with integers. And that would be a stupid work of overloading every integer
> operation for the class.

No, you can do the same thing with lists:

---
>>> a=[1]
>>> b=a
>>> a
[1]
>>> b
[1]
>>> b[0]=3
>>> a
[3]
>>>
---

but as for doing it directly? Not that I know of.

> Anyway, is it hard to provide such direct mechanism for immutable
> instances? As I understand that how it operates now:
>
> a = 10 (now a references to 10)
> b = a ( now b references to the same value(instance) 10)
> b = 20 ( now b doesn't references to 10, it references to another
> value 20. And we decrement reference counter of the value(instance) 10)
>
> So, IMHO, it's not so hard to implement Perl-like references here.
>
> And does this all mean that I should move on to Perl or any other
> language, if I need effective implementation of references :) ?

Well, if you've determined that you need to control references all the way
down to integers, then you should think about how efficient the program will
be. In general an integer on its own isn't a lot of data, and if you're
pushing around tiny little bits of information then your program will suffer
when it comes to efficiency.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>






More information about the Python-list mailing list