-2

Look at this code:

__fields = {2: '_id', 4: 'link_grabber_id', 8: 'last_read', 16: 'change_selector', 32: 'image_selector',
                64: 'link_selector', 128: 'country_id', 256: 'language_id', 512: 'news_agency_id', 1024: 'etag',
                2048: 'last_size', 4096: 'added_by', 8192: 'watermark_text', 16384: 'redirect_status',
                32768: 'rss_desc', 65536: 'last_modified', 131072: 'link', 262144: 'run_time', 524288: 'content_type',
                1048576: 'category_id', 2097152: 'enabled', 4194304: 'halt_count', 8388608: 'added_on'}

def x(criteria={}, f=0):
    f = 9
    print '2', criteria
    #var = criteria.copy()
    var = criteria

    print 'var', var
    for k, v in var.items():
                var.update({__fields[k]: v})
                del var[k]
    print '3', criteria, var

ccc = {1048576: 54}
print '1', ccc
w = 0
x(ccc, w)
print '4', ccc, w

If I use var = criteria instead of var = criteria.copy() var contains a reference to criteria which changes after changing criteria. Why it's a reference? When python use reference instead of value assignment?

ehsan shirzadi
  • 4,709
  • 16
  • 69
  • 112
  • 3
    95% of the code you posted is completely irrelevant for the question you're asking. Why all the clutter? – wvdz Aug 12 '14 at 12:37
  • @jonrsharpe: mutable and immutable objects are passed the exact same way, and neither is "by reference" in the traditional sense. – Wooble Aug 12 '14 at 12:37
  • possible duplicate (even if not apparent at first glance) of (among others) http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Foon Aug 12 '14 at 12:38
  • ehsan: You also probably want to read http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument because while your code doesn't actually display the bug mutable default arguments cause, it can if you call that `x()` function differently. – Wooble Aug 12 '14 at 12:38
  • @enrico.bacis: writing `j = – Wooble Aug 12 '14 at 12:46
  • @Wooble I removed the comment since it was adding noise, thanks – enrico.bacis Aug 12 '14 at 12:51

1 Answers1

-2

Python always uses value assignment. The issue is that the dict value is a container type and will not generate a new copy at each assignment.

Andrew Johnson
  • 3,078
  • 1
  • 18
  • 24