Anonymous Code Blocks

Introduction: So far, I have used python as a full-blown programming language. Now I like to use it to write some notes (comments) with some calculations (python code) here and there (I actually use emacs and send the current buffer again and again to the ipython executable instance).

Problem: I like to reuse some common variable names, such as "A" or "d", several times in the same document, without triggering the problem that I accidentally forgot to reassign the value to one of these variable names.

I'm still abusing class statement

# Topic one: bla bla
class _anon:
    d = 10
    A = d**2 * pi /4

# Topic two: bla bla
class _anon:
    A = d**2 * pi /4 # error is raised since d is missing

This works because the class statement creates an execution frame that works as the scope of the variable, but I wonder if there is syntax highlighted for this use case.

+5
source share
4 answers

No. Blocks and modules classand def(and in later versions, list descriptions and generator expressions are not applicable here) introduce a new area. And only classes are executed directly. So if you want to continue this controversial use of Python, you must stick with abuse class, or define functions and call them directly. Using a different file for each calculation is a little less ugly at the source code level, but maybe not worth it if the calculations are always small.

+3

globals.clear() :

>>> a = 5
>>> b = 6
>>> a
5
>>> b
6
>>> globals().clear()
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

, , , globals! globals.clear() , :

>>> globals.clear()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'globals' is not defined

. http://bytes.com/topic/python/answers/34902-how-clean-python-interpreters-environment#post129239

, Python , , , , GNU Octave.

+2

, del

d = 10
A = d**2 * pi /4
(...)
del d, A

# Topic two: bla bla

A = d**2 * pi /4 # error is raised since d is missing

" , ". " ". " - - ".

, , , " " " , ", , . , del.

+2

C/++, :

def _anon():
    d = 10
    A = d**2 * pi /4
_anon()

"" .


, :

def block(function):
    function()

:

@block
def _anon():
    d = 10
    A = d**2 * pi /4

Note that function decorators usually return a function, but this is not. As a result, the name "_anon" points to "None" after code execution, so the code block is really anonymous.

+2
source

All Articles