Object copies...
Justin Shaw
wyojustin at hotmail.com
Mon Dec 23 08:04:45 EST 2002
"DP" <pennedinil at excite.com> wrote in message
news:6af8e801.0212222321.3bd5b56f at posting.google.com...
> Hi all,
>
> Please help me clear my confusion here. I'm running the script below.
> I'm expecting to get a listing of my original object and the new
> object created by 'getdates'. Instead I'm seeing the function
> 'getdates' changing my original object, 'mydates'.
>
> Q1: Why does 'getdates' not create a copy of 'mydates' instead of
> operating on the original object? I.e., how do I change this behavior?
It boils down to the fact that lists are "mutable". Passing mutable
arguments to
functions mearly passes a referance to that object so any changes made in
the
fucntion affect the original. This behavior may seem counter-intuitive but
turns out
in practice to be quite handy. When you want a copy you need to create one
explicitly (see copy.deepcopy documentation.)
> Q2: [Unrelated] I'm trying to parse these dates into d, m, y and can't
> think of any other way but on a per-case basis. Any suggestions on a
> better aproach? I tried -
> try:
> d. m, y = Dates[i].split("/")
> except: ValueError ...<etc>
> but there are too many exceptions to the rule, which brings me back to
> a case-based algorithm.
See time.strftime.
>
> Thanks in advance.
> Dinil.
Hope that helps.
Justin
> # -----------------------------------------------------------------------
> def indexedList(list):
> return map(None, range(len(list)), list)
>
> def getdate(Dates):
> for i, j in indexedList(Dates):
> j = j.replace(".", "/")
> j = j.replace("-", "/")
> j = j.replace(" ", "/")
> Dates[i] = j
> return Dates
>
>
> if __name__ == "__main__":
> mydates = ['31082002','31.08.2002','31.08.2002',
> '30092002','30.09.2002','30.09.2002',
> '309 2' ,'30-09-2002','30-09-2002',
> '318 2' ,'31.08.2002','31/08/2002',
> '30092002','30-09-2002','30-09-2002',
> '31082002','31-08-2002','31-08-2002',
> '309 2002','30.09.2002','30.09.2002',
> '318 2002','31.08.2002','31.08.2002',
> '30092002','30.09.2004','' ,
> '31082002','31.08.02' ,'' ,
> '30092002','30.09.02' ,'30.09.2002',
> '31082002','31.08.02' ,'31.08.2002',
> '30092002','30.09.2002','30/9/2002' ,
> '31082002','31/8/2002' ,'31/8/2002' ,
> '31082002','31082002' ,'' ,
> '30092002','30092002' ,'30092002' ,
> '31082002','31.08.2002','31.08.2002'
> ]
> newdates = getdate(mydates)
> print newdates
> print mydates
More information about the Python-list
mailing list