Preventing execution of a method

MRAB google at mrabarnett.plus.com
Thu Dec 11 11:44:44 EST 2008


alex23 wrote:
> On Dec 12, 2:07 am, "Emanuele D'Arrigo" <man... at gmail.com> wrote:
>> I.e. if I have a class with two methods, doSomethingSafe() and
>> doSomethingDangerous(), is there a way to prevent another module from
>> executing doSomethingDangerous() but allow the execution of
>> doSomethingSafe()?
>>
>> My understanding is that in python this is not possible. Can you
>> confirm?
> 
> Your understanding is correct.
> 
> The Python convention is to prefix non-public methods/classes etc with
> an underscore, as in _doSomethingDangerous(). This is meant to
> indicate to anyone using your module that they shouldn't use this
> function, at least not without having a good understanding of what it
> does.
 >
You could add a little bit of protection by always passing a certain 
object into _doSomethingDangerous().

_guard = object()

def _doSomethingDangerous(g):
     if g is not _guard:
         raise Exception("Don't do that!")

That would at least stop accidental calls.



More information about the Python-list mailing list