Note that there are some explanatory texts on larger screens.

plurals
  1. POPython functions can be given new attributes from outside the scope?
    text
    copied!<p>I didn't know you could do this:</p> <pre><code>def tom(): print "tom's locals: ", locals() def dick(z): print "z.__name__ = ", z.__name__ z.guest = "Harry" print "z.guest = ", z.guest print "dick's locals: ", locals() tom() #&gt;&gt;&gt; tom's locals: {} #print tom.guest #AttributeError: 'function' object has no attribute 'guest' print "tom's dir:", dir(tom) # no 'guest' entry dick( tom) #&gt;&gt;&gt; z.__name__ = tom #&gt;&gt;&gt; z.guest = Harry #&gt;&gt;&gt; dick's locals: {'z': &lt;function tom at 0x02819F30&gt;} tom() #&gt;&gt;&gt; tom's locals: {} #print dick.guest #AttributeError: 'function' object has no attribute 'guest' print tom.guest #&gt;&gt;&gt; Harry print "tom's dir:", dir(tom) # 'guest' entry appears </code></pre> <p>Function tom() has no locals. Function dick() knows where tom() lives and puts up Harry as 'guest' over at tom()'s place. harry doesn't appear as a local at tom()'s place, but if you ask for tom's guest, harry answers. harry is a new attribute at tom().</p> <p>UPDATE: From outside tom(), you can say "print dir(tom)" and see the the tom-object's dictionary. (You can do it from <strong>inside</strong> tom(), too. So tom could find out he had a new lodger, harry, going under the name of 'guest'.)</p> <p>So, attributes can be added to a function's namespace from outside the function? Is that often done? Is it acceptable practice? Is it recommended in some situations? Is it actually vital at times? (Is it Pythonic?)</p> <p>UPDATE: Title now says 'attributes'; it used to say 'variables'. Here's a <a href="http://www.python.org/dev/peps/pep-0232/" rel="nofollow noreferrer">PEP about Function Attributes</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload