Preventing direct access to a class

Michael Hudson mwh21 at cam.ac.uk
Sun Feb 4 13:16:25 EST 2001


Daniel Klein <danielk at aracnet.com> writes:

> I have a situation where I need to prevent direct access to a class. IOW, the
> only way I wish a class to be instantiated is via another class. For example
> 
> >>> class A:
> 	pass
> 
> >>> class B:
> 	def foo(self):
> 		return A()
> 	
> >>> b = B()
> >>> a = b.foo()
> 
> ...and there might be other classes that 'return A()'.
> 
> I do not want the user to be allowed to do this...
> 
> >>>a = A()
> 
> It doesn't look like classes can be made 'private to the module' as
> I tried to define class A as 'class __A'. The user could still
> access with a=__A() (no mangling needed).
> 
> Other than placing some convoluted logic in each class, is there a way to
> accomplish this pythonic-ly?

You won't be able to do this completely.  You can make it sufficiently
hard that people won't do it by mistake, which is good enough for most
folk (it is for me).

Here's one way:

-------------------------------
class A:
 pass

class B:
 def foo(self,A=A):
  return A()

del A
-------------------------------

the class A is still there:

>>> B.foo.im_func.func_defaults 
(<class __main__.A at 0x8195024>,)

but I think you can rely on people not doing

>>> B.foo.im_func.func_defaults[0]()

accidentally <wink>.

Cheers,
M.

-- 
  I'm okay with intellegent buildings, I'm okay with non-sentient
  buildings. I have serious reservations about stupid buildings.
     -- Dan Sheppard, ucam.chat (from Owen Dunn's summary of the year)



More information about the Python-list mailing list