TypeError during assignment to attribute reference?
<p>Reading about <a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">Assignment statements</a> in the Python's docs I found this:</p>

<blockquote>
  <p>If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, <code>TypeError</code> is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily <code>AttributeError</code>).</p>
</blockquote>

<p>I'm wondering how to get this <code>TypeError</code>?</p>

<p><strong>What Python's types doesn't have routine for setting attributes?</strong></p>

<p>This code produces a <code>TypeError</code> and it seems like it is what the documentation describes:</p>

<pre><code>&gt;&gt;&gt; def f(): pass
...
&gt;&gt;&gt; f.func_globals = 0
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: readonly attribute
</code></pre>

<p>But is this <code>TypeError</code> really raised because the documentation says that? I sincerely doubt it. I guess <code>func_globals</code> implementation simply raises <code>TypeError</code> if you try to assign something to it.</p>

<p><strong>BTW...</strong></p>

<p>I would actually excpect the same in the next example, but it is an <code>AttributeError</code> instead:</p>

<pre><code>&gt;&gt;&gt; class A(object):
...     __slots__ = 'a',
...
&gt;&gt;&gt; A().b = 0
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: 'A' object has no attribute 'b'
</code></pre>

<p><strong>Update (Python 3)</strong></p>

<p>The above was in Python 2.7. In Python 3, there is no <code>func_globals</code>, so this is not applicable (you can assign anything to it).</p>

<p>What attributes function has in Python 3 seem to raise an <code>AttributeError</code> when it is read-only.</p>

<pre><code>&gt;&gt;&gt; f.__globals__ = 0
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: readonly attribute
</code></pre>

<p>This makes perfect sense to me. Perhaps this part of the documentation is just a relic as far as Python 3 is concerned.</p>

python python-3.x typeerror attr