How can one create new scopes in python

后端 未结 12 1188
渐次进展
渐次进展 2020-12-10 01:08

In many languages (and places) there is a nice practice of creating local scopes by creating a block like this.

void foo()
{
     ... Do some stuff ...

             


        
12条回答
  •  失恋的感觉
    2020-12-10 01:48

    Like so, for arbitrary name t:

    ### at top of function / script / outer scope (maybe just big jupyter cell)
    try: t
    except NameError:
        class t
            pass
    else:
        raise NameError('please `del t` first')
    
    #### Cut here -- you only need 1x of the above -- example usage below ###
    
    t.tempone = 5 # make new temporary variable that definitely doesn't bother anything else.
    # block of calls here...
    t.temptwo = 'bar' # another one...
    del t.tempone # you can have overlapping scopes this way
    
    # more calls
    t.tempthree = t.temptwo; del t.temptwo # done with that now too
    print(t.tempthree)
    # etc, etc -- any number of variables will fit into t.
    
    
    ### At end of outer scope, to return `t` to being 'unused'
    del t
    

    All the above could be in a function def, or just anyplace outside defs along a script.

    You can add or del new elements to an arbitrary-named class like that at any point. You really only need one of these -- then manage your 'temporary' namespace as you like.

    The del t statement isn't necessary if this is in a function body, but if you include it, then you can copy/paste chunks of code far apart from each other and have them work how you expect (with different uses of 't' being entirely separate, each use starting with the that try: t... block, and ending with del t).

    This way if t had been used as a variable already, you'll find out, and it doesn't clobber t so you can find out what it was.

    This is less error prone then using a series of random=named functions just to call them once -- since it avoids having to deal with their names, or remembering to call them after their definition, especially if you have to reorder long code.

    This basically does exactly what you want: Make a temporary place to put things you know for sure won't collide with anything else, and which you are responsible for cleaning up inside as you go.

    Yes, it's ugly, and probably discouraged -- you will be directed to decompose your work into a set of smaller, more reusable functions.

提交回复
热议问题