Pass by reference

iu2 israelu at elbit.co.il
Wed Dec 31 14:04:15 CET 2008


On Dec 31, 1:48 pm, "Chris Rebert" <c... at rebertia.com> wrote:
...
>
> Not really, or at the very least it'll be kludgey. Python uses
> call-by-object (http://effbot.org/zone/call-by-object.htm), not
> call-by-value or call-by-reference.
>
> Could you explain why you have to set so many variables to the same
> value (if they're None)? It's a bit strange and could be a sign that
> there's a better way to structure your program (e.g. use a
> dictionary). We might be able to offer more helpful suggestions if you
> explain.
>
> Cheers,
> Chris
>
> --

Hi, thanks for your reply.

Well, I wrote an application that talks via UDP to several targets
(embedded). Currently there are only two of them connected to my PC,
but there could be more. Let's call them target 1 and target 2.

Now, each target has its own IP address, and is connected straight to
my PC, no DHCP or common bus or whatsover
The GUI of my application enables the user to enter the IP for each
target.
The user can disconnect one target, and then connect a different one
with a different IP.
Let's say he replaces target 2 with a different one. Then he must tell
the python app that target 2 now has a different IP. He does that by
entering a different IP for target 2 in the GUI.

When the app sends data to a target, it must know whether to create a
new socket or use the previous one for that target. It deduces this by
observing a change in the IP address in the GUI for that target.

For the 2 targets I have the variables comm1 and comm2. They are of
some class I wrote, representing many properties of the communication,
including the IP address.
There is one function that sends data, and it receives a commX var
(comm1 or comm2) as the means for sending the data.
Before sending the data the function needs to initilze commX (if it is
still None), or creating it a new, if it sees that the IP for that
target has changed.

Something like this:

def send_data(comm, data, current_ip_from_gui):
  if comm is None:
    # I want to assign comm a new MyComm
  elif comm.ip != current_ip_from_gui:
    # I want to re-assign a new MyComm that uses the new IP
  comm.socket.SendTo(comm.addr, data)  # eventually send the data

I could re-design it to have send_data be a method of MyComm. But I
don't think I should, beacuse I planned MyComm to have only
properties. I'd like functions to receive it and manipulate it. MyComm
could also be a mere string just as well...
Since I can apply this idiom in C (pointer), Lisp (macro),  tcl
(upvar) and C# (ref) I wondered what the python way was.

But I guess I can achieve this using a class holding my vars, maybe
like this:

class CommVars:
  comm1 = None
  comm2 = None

myvars = CommVars()

and then change a value like this:

def set_var(dict0, varname, val):
  dict0[varname] = val

set_var(myvars.__dict__, 'comm1', MyComm(...))









More information about the Python-list mailing list