Is it possible (and wise) to extend the None-type ?
John Machin
sjmachin at lexicon.net
Wed Nov 26 13:50:26 EST 2008
On Nov 27, 4:55 am, Stef Mientki <stef.mien... at gmail.com> wrote:
> hello,
>
> I've the idea that I always have a lot of useless code in my programs,
> like the next example.
>
> def _On_Menu_File_Open ( self, event = None ):
> if event :
> event.Skip ()
>
> instead of
>
> def _On_Menu_File_Open ( self, event = None ):
> event.Skip ()
>
> So I would like to extend the None-type (if that's possible),
> with a dummy Skip() method.
>
> Is it wise to do ?
No.
> If not what are the disadvantages ?
Assume that as well as your Event class, you also have a Foo class
with a dothis method and a Bar class with a dothat1 and a dothat2
method: you would need to extend the None-type (if that's possible) to
have dummy skip, dothis, dothat1 and dothat2 methods. Each time you
invent a new class, you need to consider adding one or more new dummy
methods to your extended None-type.
Alternative (if you *really* want to save the explicit test) is to
attach the behaviour modification to the *relevant* class:
class NonEvent(Event):
def do_nothing(self):
pass
skip = jump = hop = waltz = saunter = do_nothing
def __len__(self):
return 0
NON_EVENT = NonEvent()
del NonEvent
# later:
def amethod(self, event=NON_EVENT):
if event: # still works thanks to __len__ above
event.skip()
# now can avoid test, if desired
event.skip()
HTH ... BTW, ever heard of PEP 8?
Cheers,
John
More information about the Python-list
mailing list