global and None

Paul McGuire ptmcg at
Tue Dec 23 16:13:10 CET 2003

"Francis Avila" <francisgavila at> wrote in message
news:vug3s0pa1q1sa3 at
> Leo Yee wrote in message ...
> >My purpose is to init g. This is very useful when we cannot construct a
> >global variable.
> Like when? And why?

One reason is to do late construction/initialization, or lazy
initialization.  If an object is very time-consuming to construct, don't
create it at import time, wait until it is actually used.  Once created,
save it in a global so that you don't have to re-create it every time.

This is sort of a quick-and-dirty singleton pattern.  I do a very similar
thing to construct my pyparsing grammar *once*, then save it in the global
and re-reference it on subsequent calls.

    sqlGrammar = None
    def getSQLGrammar():
        global sqlGrammar
        if sqlGrammar is None:
            # construct SQL grammar - this only needs to happen once
            sqlGrammar = CaselessLiteral("select") + <blah, blah, blah>
        return sqlGrammar

    def test( sqlstring ):
        return getSQLGrammar().parseString( sqlstring )

    test( "SELECT * from XYZZY, ABC" )
    test( "select * from SYS.XYZZY" )
    test( "Select A from Sys.dual" )

-- Paul

More information about the Python-list mailing list