Creating an instance when the argument is already an instance.

Chris Angelico rosuav at
Thu Jul 5 12:47:52 CEST 2012

On Thu, Jul 5, 2012 at 8:29 PM, Olive <diolu at> wrote:
> I am creating a new class: package (to analyse the packages database in
> some linux distros). I have created a class package such that
> package("string") give me an instance of package if string is a correct
> representation of a package. I would like that if pack is already an
> instance of package then package(pack) just return pack.

One way would be to make the name "package" actually a wrapper
function, not the class itself:

>>> class _package:
	def __init__(self,arg):
		# blah blah

>>> def package(arg):
	if isinstance(arg,_package): return arg
	return _package(arg)

>>> a=package("Test")
>>> b=package(a)
>>> a is b

The leading underscore is a common convention meaning "private
implementation detail".

Chris Angelico

More information about the Python-list mailing list