Pass by reference
Chris Rebert
clp at rebertia.com
Wed Dec 31 08:29:36 EST 2008
On Wed, Dec 31, 2008 at 5:04 AM, iu2 <israelu at elbit.co.il> wrote:
<snip>
> 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.
Based on the naming alone (though further corroborated by your
details), I can recommend that you use a dictionary instead of
variables for the commX-s.
Basically, remove the comm1, comm2, etc variables and instead do (you
might want to use a defaultdict or list rather than a plain dict):
comms = {1 : MyComm(...), 2 : None}
>
> 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
Instead that becomes:
def send_data(comms, id_num, data, current_ip_from_gui):
if comms[id_num] is None:
comms[id_num] = MyComm(...)
elif comms[id_num].ip != current_ip_from_gui:
comms[id_num] = MyComm(current_ip_from_gui, ...)
comm = comms[id_num]
comm.socket.SendTo(comm.addr, data) # eventually send the data
<snip>
> But I guess I can achieve this using a class holding my vars, maybe
> like this:
That's similar to what I'm suggesting, but mine has less indirection.
Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
More information about the Python-list
mailing list