Preface:
So far I’ve used Python as a full scale programming language. Now I like to use it to write down some notes (comments) with some calculation (Python code) here and there (I’m actually using Emacs and send the current buffer again and again to a running IPython instance).
The problem: I like to reuse some common variable names like ‘A’ or ‘d’ multiple times within the same document without running into the problem that I accidentally forget to reassign the value to one of these variable names.
I so far abuse the 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, since a class statement creates an execution frame which works as a variable scope, but I wonder if there is dedicated syntax for this use case.
No. Only
classanddefblocks and modules (and in more recent versions, list comprehensions and generator expressions – not appliable here though) introduce a new scope. And only classes execute directly. So if you want to continue this debatable use of Python, you’ll have to stick with abusingclass, or define functions and call them directly. Using a different file for each calculation is slightly less ugly at source code level, but propably not worth it if the calculations are always that small.