473,793 Members | 2,922 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When is it a pointer (aka reference) - when is it a copy?

Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

...some_huge_li st is a huge list...
some_huge_list[0]=1
aref = some_huge_list
aref[0]=0
print some_huge_list[0]

we know that the answere will be 0. In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)? Can
I "reference" it somehow? Should I assume that:

aref = _any_type_other _than_simple_on e

be a reference, and not a copy?

Thanks,

Sep 13 '06 #1
12 1641
John Henry írta:
Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

...some_huge_li st is a huge list...
some_huge_list[0]=1
aref = some_huge_list
aref[0]=0
print some_huge_list[0]

we know that the answere will be 0. In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)? Can
I "reference" it somehow? Should I assume that:

aref = _any_type_other _than_simple_on e

be a reference, and not a copy?
The short answer is that you need to keep the immutable value inside a
mutable object.

The long answer:

a.) You can reference the immutable object just like any object, but you
cannot change the immutable object. For instance, when you do

a = 1
a += 2

then you are rebinding the variable 'a' to a different object (namely,
the 2 int object.)

b.) You can however, keep a reference to your current immutable object
inside a mutable object. In many cases, the mutable object will be a
namespace dictionary.

A module is a very simple example:

a = 1
def f1():
global a
a += 1

def f2():
global a
a += 10

f1()
f2()
print a # prints 12

Notice that the "a+=10" will actually rebind the variable to a different
object.

In other cases, you will be using an object or a class:

class A(object):
a = 5

def inc_id(obj):
obj.id += 1

a = A() # a.id is 5 here
a.id = 4 # makes a.id a reference to 4
inc_id(a) # makes a.id a reference to 5 again
Best,

Laszlo

Sep 13 '06 #2
John Henry wrote:
Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

...some_huge_li st is a huge list...
some_huge_list[0]=1
aref = some_huge_list
aref[0]=0
print some_huge_list[0]

we know that the answere will be 0. In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)? Can
I "reference" it somehow? Should I assume that:

aref = _any_type_other _than_simple_on e

be a reference, and not a copy?
Yes. Attributes are always object references. The assignment is actually
the binding of a specific object to a name in some namespace, (r to an
element of a sequence or other container object.

This applies *whatever* the type of the RHS experession: the expression
is evaluated to yield an object, and a reference to the object is stored
in the name or container element.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 13 '06 #3
Thanks for the reply, both to Laszlo and Steve.

Okay, I understand what you're saying.

But what if I need to make a "pointer" to a simple variable.

For instance, in C:

int i=1
int *j=&i

*j = 2
print i

and you get 2 printed.

In Python,

i=1
j=i
j=2
print i

and you get 1 printed.

So, if I understand you correctly, I must make the reference to a more
elaborate representation. Like:

i=[1,]
j=i
j[0]=2
print i

in order to get 2 printed.

Correct?
Steve Holden wrote:
John Henry wrote:
Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

...some_huge_li st is a huge list...
some_huge_list[0]=1
aref = some_huge_list
aref[0]=0
print some_huge_list[0]

we know that the answere will be 0. In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)? Can
I "reference" it somehow? Should I assume that:

aref = _any_type_other _than_simple_on e

be a reference, and not a copy?
Yes. Attributes are always object references. The assignment is actually
the binding of a specific object to a name in some namespace, (r to an
element of a sequence or other container object.

This applies *whatever* the type of the RHS experession: the expression
is evaluated to yield an object, and a reference to the object is stored
in the name or container element.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
Sep 13 '06 #4
On 2006-09-13, John Henry <jo**********@h otmail.comwrote :
Thanks for the reply, both to Laszlo and Steve.

Okay, I understand what you're saying.

But what if I need to make a "pointer" to a simple variable.
There's no such thing as a "simple variable". There are
mutable objects and immutable objects. Names are bound to
objects.

x = 3

The name "x" is bound to an immutable integer object who's
value is 3.
For instance, in C:

int i=1
int *j=&i

*j = 2
print i

and you get 2 printed.

In Python,

i=1
The name "i" is bound to an immutable integer object who's value is 1.
j=i
The name "j" is bound to an immutable integer object who's
value is 1. That may or may not be the same object to which
"i" is bound.
j=2
Now the name "j" is bound to an immutable integer object who's
value is 2. Rebinding the name "j" to a different object has
no effect on the object to which "i" is bound.
print i

and you get 1 printed.
Because you've changed neither the object to which "i" is bound
nor the value of that object (you can't change the values of
integer objects).
So, if I understand you correctly, I must make the reference
to a more elaborate representation. Like:

i=[1,]
j=i
j[0]=2
print i

in order to get 2 printed.

Correct?
I suppose, for some values of "correct". You've bound the
names "i" and "j" to the same mutable object, then mutated that
object. Afterwards "i" and "i" still refer to that mutated
object.

That'll work as a rather clumsy imitation of the C code, but I
don't really see what it is you're trying to accomplish. Trying
to write C code using Python isn't going to be fun or productive[1].

When using Python, you should write Python code. ;)

If you'll explain the actual problem you're trying solve for
which you think you need C-style "pointers", then somebody will
be happy to show you how that problem is solved using Python.

[1] There are people here who probably think it fun, but only
as a brain-teaser.

--
Grant Edwards grante Yow! After THIS, let's go
at to PHILADELPHIA and have
visi.com TRIPLETS!!
Sep 13 '06 #5
Thanks for the reply, Grant.

I am not doing things like that - I am just trying to clear up in my
mind the Python concepts.

I understand it now.

Grant Edwards wrote:
On 2006-09-13, John Henry <jo**********@h otmail.comwrote :
Thanks for the reply, both to Laszlo and Steve.

Okay, I understand what you're saying.

But what if I need to make a "pointer" to a simple variable.

There's no such thing as a "simple variable". There are
mutable objects and immutable objects. Names are bound to
objects.

x = 3

The name "x" is bound to an immutable integer object who's
value is 3.
For instance, in C:

int i=1
int *j=&i

*j = 2
print i

and you get 2 printed.

In Python,

i=1

The name "i" is bound to an immutable integer object who's value is 1.
j=i

The name "j" is bound to an immutable integer object who's
value is 1. That may or may not be the same object to which
"i" is bound.
j=2

Now the name "j" is bound to an immutable integer object who's
value is 2. Rebinding the name "j" to a different object has
no effect on the object to which "i" is bound.
print i

and you get 1 printed.

Because you've changed neither the object to which "i" is bound
nor the value of that object (you can't change the values of
integer objects).
So, if I understand you correctly, I must make the reference
to a more elaborate representation. Like:

i=[1,]
j=i
j[0]=2
print i

in order to get 2 printed.

Correct?

I suppose, for some values of "correct". You've bound the
names "i" and "j" to the same mutable object, then mutated that
object. Afterwards "i" and "i" still refer to that mutated
object.

That'll work as a rather clumsy imitation of the C code, but I
don't really see what it is you're trying to accomplish. Trying
to write C code using Python isn't going to be fun or productive[1].

When using Python, you should write Python code. ;)

If you'll explain the actual problem you're trying solve for
which you think you need C-style "pointers", then somebody will
be happy to show you how that problem is solved using Python.

[1] There are people here who probably think it fun, but only
as a brain-teaser.

--
Grant Edwards grante Yow! After THIS, let's go
at to PHILADELPHIA and have
visi.com TRIPLETS!!
Sep 13 '06 #6
Grant Edwards wrote:
On 2006-09-13, John Henry <jo**********@h otmail.comwrote :
So, if I understand you correctly, I must make the reference
to a more elaborate representation. Like:

i=[1,]
j=i
j[0]=2
print i

in order to get 2 printed.

Correct?

I suppose, for some values of "correct". You've bound the
names "i" and "j" to the same mutable object, then mutated that
object. Afterwards "i" and "i" still refer to that mutated
object.
Another way to explain why this is so, without fuzzy terms like "a more
elaborate representation" , is that although the statements "x = 2" and
"x[0] = 2" look both as "assignment s" syntactically, they work quite
differently under the hood. The former binds a name ("x") to an object
("2"). The latter is syntactic sugar for a method call:
x.__setitem__(0 ,2). If x happens to be a list, this is equivalent to
calling the unbound method list.__setitem_ _(x,0,2) which, as you
already know, mutates the list x. The important thing to remember
though is that the effect of something like "x[0] = 2" depends on the
type of x. Any class can define a __setitem__(ind ex,value) method with
arbitrary semantics; it is not (and cannot be) forced to mutate x. The
bottom line is that you can't tell in advance what "x[0] = 2" will do
without knowing the type of x. A binding OTOH like "x=2" has always the
same semantics: make the name "x" refer to the object "2".

Similarly to "x[0] = 2", something like "x.foo = 2" looks like an
assignment but it's again syntactic sugar for a (different) method
call: x.__setattr__(' foo',2). All the above about __setitem__ hold for
__setattr__ too.
HTH,
George

Sep 14 '06 #7
Dennis Lee Bieber wrote:
References to lists, dictionaries, and class instances (which are,
in a way, just an expanded dictionary) are "mutable"
careful: it's not the *reference* that's mutable, it's the object.

the *only* difference between mutable and immutable objects is that
the latter don't provide any methods that you could use to modify their
contents.

plain assignment (name=) *never* modifies objects, and *never* copies
objects.

this article

http://effbot.org/zone/python-objects.htm

may be useful for those who haven't already seen it.

</F>

Sep 14 '06 #8
John Henry a écrit :
Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

...some_huge_li st is a huge list...
some_huge_list[0]=1
aref = some_huge_list
aref[0]=0
print some_huge_list[0]

we know that the answere will be 0. In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)? Can
I "reference" it somehow? Should I assume that:

aref = _any_type_other _than_simple_on e

be a reference, and not a copy?

Thanks,
That's easy. In Python, every variable is a depth one pointer. Every
variable is of the type (PyObject*)

Of course, since numbers and strings are immutable, that pointer is
useless to push back the modifications you've done.

You need a PyObject** ? Use a one element list instead and manipulate it
like that : number_ref[0] = new_value
instead of that : number_ref = [new_value]

Sep 14 '06 #9
John Henry wrote:
Hi list,

Just to make sure I understand this.

Since there is no "pointer" type in Python, I like to know how I do
that.

For instance, if I do:

...some_huge_li st is a huge list...
some_huge_list[0]=1
aref = some_huge_list
aref[0]=0
print some_huge_list[0]

we know that the answere will be 0. In this case, aref is really a
reference.

But what if the right hand side is a simple variable (say an int)? Can
I "reference" it somehow? Should I assume that:

aref = _any_type_other _than_simple_on e

be a reference, and not a copy?
short answer : Python won't copy anything until explicitely asked to.

Longer answer:

First, there's nothing like "simple" type or var in Python. All that you
have are names and objects. The statement 'some_name = some_obj' "binds"
together 'some_name' and 'some_obj' - IOW, once this statement is
executed, 'some_name' refers to ('points to') 'some_obj' (think of it as
an equivalent of 'globals['some_name'] = some_obj', and you won't be far
from truth). This is how it works for all and any type.

What you really need to understand is that in Python, a 'variable' is
*only* a name. It's *not* the object itself.

Now we have mutable and immutable types. Immutable types are (mainly)
numerics, strings and tuples. As the qualificative implies, one cannot
change the state (ie value) of an object of immutable type. Also, note
that mutating (modifying the state of an object) and assignment (binding
a name to an object) are two very different things. Rebinding a name
just make it points to another object, it doesn't impact the object
previously bound to that name (not directly at least, cf memory management).

To come back to your code snippet:

# binds name "some_huge_list " to an empty list
some_huge_list = []

# mutate the list object bound to name 'some_huge_list '
some_huge_list[0]=1

# binds name "aref" to the list object
# already bound to name 'some_huge_list '
aref = some_huge_list

# you can verify that they are the same object:
assert aref is some_huge_list
# nb : in CPython, id(obj) returns the memory address of obj
# FWIW, identity test (obj1 is obj2) is the same as
# equality test on objects id (ie id(obj1) == id(obj2))
print id(aref)
print id(some_huge_li st)

# mutate the list object bound to names 'aref' and 'some_huge_list '
aref[0]=0

# Now lets go a bit further and see what happens when we rebind
# some_huge_list:

some_huge_list = []

# does this impact aref ?
print aref
aref is some_huge_list

# well, obviously not.
# name 'aref' is still pointing to the same object:
print id(aref)
# but name 'some_huge_list ' now points to another object:
print id(some_huge_li st)

To answer your question : it works *exactly* the same way for immutable
objects:

a = 333000000000000
b = a
print b is a # True

b = 333000000000000
print b is a # False

The only difference here is that you can not alter the value of (IOW
mutate) an immutable object. So having a reference to it won't buy you
much... If you want to "share" an immutable object, you have to embed it
into a mutable container and share this container:

a = [333000000000000]
b = a
b[0] = 333000000000001
assert a is b
assert a[0] is b[0]
print a[0]

As a side note : when passing arguments to a function, the arguments
themselves are (references to) the original objects, but the names are
local to the function, so mutating an object passed as argument will
effectively impact the object (if it's mutable of course !-), but
rebinding the name inside the function won't change anything outside the
function :

def test(arg)
# really mutates the object passed in
arg[0] = 42
print "in test : arg is %s (%s)" % (arg, id(arg))

# only rebinds the local name 'arg'
arg = []
print "in test : now arg is %s (%s)" % (arg, id(arg))

def runtest():
obj = ["Life, universe and everything"]
print "in runtest : obj is %s (%s)" % (obj, id(obj))
print "calling test with obj:"
test(obj)
print "in runtest: now obj is %s (%s)" % (obj, id(obj))

Here again, if you want your function to alter the value of an immutable
object passed as argument, you have to embed it in a mutable container.
*But* this is usually useless - it's perfectly legal for a Python
function to return multiple values :

def multi(x):
return x+1, x*2

y, z = multi(42)
print "y : %s - z : %s" % (y, z)

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Sep 14 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2446
by: Jim Campbell | last post by:
Suppose I wanted to a class to contain a pointer, but I didn't want to make the copy constructor or assignment operator reinitialize this pointer. (Think of a class that contains an mmapped pointer - having to duplicate the memory could be very expensive.) Instead, I wanted only the non-copy construction to create the pointer, and have copies of the object, achieved through either copy construction or assignment, refer to the pointer...
10
2276
by: Tony Johansson | last post by:
Hello Experts!! This class template and main works perfectly fine. I have this class template called Handle that has a pointer declared as T* body; As you can see I have a reference counter in the class template so I know how many references I have to the body. In my case it's the Integer wrapper class which is the body. This template works for many different types. The one that I use is named Integer and is a Wrapper for an int. The...
9
3004
by: Sandy | last post by:
Hi, In one of my interview I was asked a question, whether using pointers for argument is efficient then reference or not. i.e. void fun(Complex *p) void fun(Complex &ref) can somebody tell me which one will be more efficient and why? as far as i know both must be same, because i read somewhere that internally
2
1539
by: Bruno van Dooren | last post by:
Hi All, i have some (3) different weird pointer problems that have me stumped. i suspect that the compiler behavior is correct because gcc shows the same results. ---------------------------------------------- //example 1: typedef int t_Array; int main(int argc, char* argv)
20
2130
by: Joe Van Dyk | last post by:
Is there some rule of thumb about when to use pointers to an object and when to use a reference* to an object when a class needs to have objects as data members? Example: class A { B* b_ptr; B b; vector<B*> vector_ptrs;
14
2417
by: key9 | last post by:
Hi All On coding , I think I need some basic help about how to write member function . I've readed the FAQ, but I am still confuse about it when coding(reference / pointer /instance) , so I think I need some "template". Sorry for my coding experience in c++
11
1925
by: Brian | last post by:
Dear Programmers, I have a class with a pointer to an array. In the destructor, I just freed this pointer. A problem happens if I define a reference to a vector of this kind of class. The destruction of the assigned memory seems to call the class destructor more than once. I don't know the reason or whether I used the vector class correctly. Attached is my program. Thanks for your help. Regards,
5
1698
by: nagrik | last post by:
Hello group, Last week I picked up a thread, which pointed out that if a copy constructor is created with pointers instead of reference, there is a danger of it going in infinite recursion. My observation: 1. Compiler does not complain.
32
2571
by: Joe | last post by:
I am just starting to use Object Oriented PHP coding, and I am seeing quite often the following (this example taken from a wiki): $wakka =& new Wakka($wakkaConfig); What exactly is the =&, and why is it different from = ?
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10433
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10212
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6777
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4112
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.