notbrainsurgery (notbrainsurgery) wrote,
notbrainsurgery
notbrainsurgery

python scoping

Take a look at the following Python code:


class X:
    def x(self):
        print b
        #b=2

b=1
X().x()


It compiles and runs just fine. However if you would remove comment from line "b=2", magically expression "print b" on the previous line will become invalid and compiler will give you an error: for it "UnboundLocalError: local variable 'b' referenced before assignment".

Of course the language spec, explains this phenomenon:

"If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations."

But this does not make this right. It goes against every instinct of an experienced developer.
Tags: programming languages, python
Subscribe

  • Poor Man Video Thumbnail Generation

    If you are building yet another YouTube-like service, eventually, you will be facing the problem of generating thumbnails for video clips. The…

  • furl.net -> del.icio.us

    I am using FURL as my primary bookmark manager. The most attractive feature to me is that it saves the actual copy of a page as I have seen it. So…

  • inheriting lexical states

    While writing small grammar recently using JavaCC I realized that I am missing one very convenient feature: inheritance of lexical states. For…

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 2 comments