import from question

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jan 16 16:50:18 EST 2008


Tobiah <toby at tobiah.org> writes:

> Ben Finney wrote:
> > Tobiah <toby at tobiah.org> writes:
> >
> >> This is a little surprising. So "from mod import *" really copies
> >> all of the scalars into new variables in the local namespace.
> >
> > No. Nothing is copied. All the objects (remembering that in Python,
> > *everything* is an object) created by the code in module 'mod' are
> > given names in the current namespace.
> 
> Yeah, copied.  Just as in:
> 
> >>> a = 3
> >>> b = a
> >>> a = 5
> >>> b
> 3
> >>>

Again, those aren't copies. There is only one instance of each value,
referenced by multiple names. This is made clearer by using a mutable
value:

    >>> a = [1, 2, 3]
    >>> b = a
    >>> c = b
    >>> a = [4, 5, 6]
    >>> a, b, c
    ([4, 5, 6], [1, 2, 3], [1, 2, 3])

    >>> a.append("spam")
    >>> b.append("eggs")
    >>> a, b, c
    ([4, 5, 6, 'spam'], [1, 2, 3, 'eggs'], [1, 2, 3, 'eggs'])

The value referenced by 'b' and 'c' is one instance; they don't have
copies of the value. Assignment binds a reference to a value, it
doesn't make a copy.

A "copy" is what's implemented by the standard library 'copy' module,
hence the name.

-- 
 \       "Whenever you read a good book, it's like the author is right |
  `\   there, in the room talking to you, which is why I don't like to |
_o__)                                read good books."  -- Jack Handey |
Ben Finney



More information about the Python-list mailing list