Classes as namespaces?
pmaupin at gmail.com
Sat Mar 27 19:22:09 CET 2010
On Mar 27, 12:10 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 3/27/2010 7:28 AM, Jonathan Hartley wrote:
> > On Mar 26, 6:26 pm, Luis M. González<luis... at gmail.com> wrote:
> > But defining and then calling the function like that is a tad
> > cumbersome. So I was wondering about:
> > x = 1
> > class account_for_non_square_pixels:
> > ((some complex logic))
> > y = 2
> The assignments within the class are performed within
> a new local namespace.
I could be misunderstanding, but I think that may be the point. When
you have what is basically a bunch of linear logic in Python,
sometimes it makes sense to break the logic up into separate
namespaces, such that you don't pollute the global namespace too badly
(which could cause obscure failures due to inadvertently reusing a
variable name which is not properly initialized on the second use).
As the OP mentioned, functions are typically used for this, but then
you have to decide if you are going to put all your functions above
all the rest of the code, or in-line, which is where they belong
according to the flow. Either decision has drawbacks -- it is jarring
to see functions defined in the middle of a code flow, but it requires
extra work to page up and down to see code that is logically in the
middle of a code flow, but has been moved out to a sub-function
> So moving non-toy code within a class block
> will typically fail.
I think, as with moving non-toy code into a function, the point may be
to *force* (more obvious) failures when something is screwed up,
rather than allowing the silent failures that can easily occur with a
large number of only marginally related variables in one big
I have done what (I think) the OP is suggesting in the distant past.
I don't know why I don't do it any more -- perhaps it is more of a
comfort thing, or maybe I have gotten better at choosing the right
abstraction points for the function boundaries so that I don't always
need to read the function code when I am reading the code that invokes
it. But in any case, I don't personally think that:
a = 27
b = 30
c = a + b
d = DoMoreComputation.c
is a terrible, ugly thing, although it is not my current preference.
More information about the Python-list