Just noticed an odd little problem. Instead of explaining it, take a look at this IDLE run:

>>> ================================ RESTART ================================
>>> class test:
	eggs = True

	
>>> var1 = test()
>>> var2 = "text"
>>> type(var2)
<type 'str'>
>>> type(var2) == str
True
>>> type(var1)
<type 'instance'>
>>> type(var1) == instance

Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    type(var1) == instance
NameError: name 'instance' is not defined

What's with that?

Recommended Answers

All 3 Replies

Class instances have to be tested differently, since you also have to supply the class info (instance of what?):

>>> class Test:
...     pass
... 
>>> t = Test()
>>> type(t)
<type 'instance'>
>>> isinstance(t, Test)
True
>>>

If you use the new style class, this becomes more apparent:

>>> class Test(object):
...     pass
... 
>>> t = Test()
>>> type(t)
<class '__main__.Test'>
>>> isinstance(t, Test)
True
>>>

The type function documentation says:
type( object)
Return the type of an object. The return value is a type object. [...]

So. Object str happens to be a type object. There is no instance type in the global scope however.

If you want to have all types, then:

import types
type(var1)==types.InstanceType
True

Slate is right, his approach works with the old style class format:

>>> import types
>>> class Test: pass
... 
>>> t = Test()
>>> type(t) == types.InstanceType
True

But does not work with the new style class:

>>> import types
>>> class C(object): pass
... 
>>> c = C()
>>> type(c) == types.InstanceType
False
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.