preventing creation of instance

Jeff Epler jepler at unpythonic.net
Wed Jun 18 02:44:32 CEST 2003


I'm not sure the final block (abel) is guaranteed to work, because gc might
collect the old adam later rather than sooner.  This might depend on
whether 'test' objects are involved in cycles.

You must use __new__ to return a non-instance when calling the class like
it was a constructor.  You could raise an exception in __init__ if you'd
rather...

$ python mirko.py
new [] adam
new ['adam'] eve
new ['adam', 'eve'] adam
new ['eve'] adam


import weakref

class test(object):
	names = weakref.WeakValueDictionary()
	def __init__(self, name):
		pass

	def __new__(cls, name):
		print "new", cls.names.keys(), name
		if cls.names.has_key(name): return None
		ret = super(test, cls).__new__(cls, name)
		cls.names[name] = ret
		return ret

adam = test("adam")
eve  = test("eve")
cain  = test("adam")

assert eve is not None
assert adam is not None
assert cain is None

del adam

abel = test("adam")
assert abel is not None





More information about the Python-list mailing list