Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assignment in python

Tags:

python

I know that "variable assignment" in python is in fact a binding / re-bindign of a name (the variable) to an object.

This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object?

I guess there is no need for that in python:

  1. Inmutable objects cannot be 'assigned to' since they can't be changed

  2. Mutable objects could potentially be assigned to, since they can change, and this could be useful, since you may want to manipulate a copy of dictionary separately from the original one. However, in these cases the python philosophy is to offer a cloning method on the mutable object, so you can bind a copy rather than the original.

So I guess the answer is that there is no assignment in python, the best way to mimic it would be binding to a cloned object

I simply wanted to share the question in case I'm missing something important here

Thanks

EDIT:

Both Lie Ryan and Sven Marnach answers are good, I guess the overall answer is a mix of both:

For user defined types, use the idiom:

a.dict = dict(b.dict)

(I guess this has problems as well if the assigned class has redefined attribute access methods, but lets not be fussy :))

For mutable built-ins (lists and dicts) use the cloning / copying methods they provide (eg slices, update)

finally inmutable built-ins can't be changed so can't be assigned

I'll choose Lie Ryan because it's an elegant idiom that I hadn't thought of.

Thanks!

like image 548
xuloChavez Avatar asked May 29 '26 08:05

xuloChavez


1 Answers

I think you are right with your characterization of assignment in Python -- I just would like to add a different method of cloning and ways of assignment in special cases.

"Copy-constructing" a mutable built-in Python object will yield a (shallow) copy of that object:

l = [2, 3]
m = list(l)
l is m
--> False

[Edit: As pointed out by Paul McGuire in the comments, the behaviour of a "copy contructor" (forgive me the C++ terminology) for a immutable built-in Python object is implementation dependent -- you might get a copy or just the same object. But because the object is immutable anyway, you shouldn't care.]

The copy constructor could be called generically by y = type(x)(x), but this seems a bit cryptic. And of course, there is the copy module which allows for shallow and deep copies.

Some Python objects allow assignment. For example, you can assign to a list without creating a new object:

l = [2, 3]
m = l
l[:] = [3, 4, 5]
m
--> [3, 4, 5]

For dictionaries, you could use the clear() method followed by update(otherdict) to assign to a dictionary without creating a new object. For a set s, you can use

s.clear()
s |= otherset
like image 174
Sven Marnach Avatar answered May 31 '26 21:05

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!