Can Python function return multiple data?
Chris Angelico
rosuav at gmail.com
Sat Jun 6 01:29:08 EDT 2015
On Sat, Jun 6, 2015 at 2:50 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> This does not happen:
>
> mylist = []
> mytuple = (None, 1, mylist)
> mylist.append(0)
> => raises an exception
>
> The *tuple* is immutable, not the list.
What you could have is a "FrozenList" (by analogy with frozenset),
something like this:
class FrozenList(tuple):
def __new__(*a, **kw):
self = tuple.__new__(*a, **kw)
hash(self) # If error, disallow construction
return self
That would raise the error at the moment of mytuple's creation, not at
mylist's mutation, but that's about as close as I can think of to a
"this truly must be immutable" object in Python. And of course, any
object can lie (or be mistaken) about its hashability and mutability:
>>> def adder(x, inc=1): return x+inc
...
>>> hash(adder)
-9223363254790714706
>>> FrozenList((adder,))
(<function adder at 0x7fcbbcf0aae8>,)
>>> descr = {adder: "Add 1 to a number"}
Looks immutable to me.
>>> adder.__defaults__=2,
>>> next(iter(descr))(6)
8
Oops.
ChrisA
More information about the Python-list
mailing list