Preventing class methods from being defined
bokr at oz.net
Mon Jan 16 20:20:20 EST 2006
On Sun, 15 Jan 2006 19:23:30 -0800, David Hirschfield <davidh at ilm.com> wrote:
>I should have explicitly mentioned that I didn't want this particular
>solution, for a number of silly reasons.
>Is there another way to make this work, without needing to place an
>explicit "if allowed" around each method definition?
Seems like you can
a. define the class with all methods defined within, and use a metaclass to prune
out the ones you don't want, which Alex provided.
b. define the class with conditional execution of the method definitions, which you just rejected.
c. define the class with no iffy methods at all, and add them afterwards
c1. in a metaclass that adds them and possibly also defines them for that purpose
c2. by plain statements adding method functions as class attributes
d. define all the methods normally, but monitor attribute access on the class and raise
attribute error for the methods that aren't supposed to be there.
e. raise an exception conditionally _within_ methods that aren't supposed to be there, if called.
What would you like?
BTW, defining the method functions someplace other than within the body of the class whose methods
they are to become has some subtleties, since the functions can potentially refer to different
global scopes than that of the class (e.g. if you take the functions from an imported module)
and/or use closure-defined cell variables (e.g. if the method function is defined within a factory function).
This can be used to advantage sometimes, but needs good documentation to be clear for the next code maintainer ;-)
I guess I should re-read your original requirements that led to thes design ideas.
More information about the Python-list