Which usage of isinstance is correct?

x = {}
isinstance(x,type(dict))

or

isinstance(x,dict)

The latter:

x = {}
print type(x)
print isinstance(x, dict)
print isinstance(x, type(dict))

Yields:

<type 'dict'>
True
False
1 Like

That’s what I thought. The latter is correct when used in components and script console.
But from a project module, the first one works and the second does not.

In a project module:

isinstance(x,dict)

Yields:

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

Is there any chance you’ve accidentally used ‘dict’ as a variable name in that module? That would replace the built-in name.

It does not look like it. Should a call to locals() help identify this?

Yes, or just "print dict"

Hmm… Ok, removing line #2 fixed the issue.
print dict was returning a dictionary of all the modules in ‘project.states’.
Below function is used as a decorator.

from project.states import utility as states
#from project.states import *

def managementLock(func):
	def fake(*args, **kwargs):
		arg1,arg2='n/a','n/a'
		if isinstance(args[0],dict): arg1,arg2=args[0]['Source'],args[0]['Target']
		else: arg1,arg2=args[0],args[1]
		project.activity.notify(project.activity.LOCK_IS_BOTTLENECK,[arg1,arg2])
		return [False, "%s,%s locked by management" % (arg1,arg2)]
		
	def inner(*args, **kwargs):
		print locals()
		print dict
		if isinstance(args[0],dict): arg1,arg2=args[0]['Source'],args[0]['Target']
		else: arg1,arg2=args[0],args[1]
		if isLocked(arg1,arg2):
			return fake(*args, **kwargs)
		else:
			return func(*args, **kwargs)

	return inner

That would suggest that somewhere at the top level of project.states, something is assigning to dict.

1 Like

In general, try to avoid from x.y.z import *. You can break your code in unexpected ways.

I just searched my code base, and didn’t need to use import * once.

2 Likes

Agreed, shame on me. Last year I ran into some other issue with import *. I forgot what problems it caused, but yeah.

Found my other import * issue…
http://forum.inductiveautomation.com/t/jython-import-behavior-in-custom-component-script/15688

Another reason to avoid it is that it doesn't work with java imports.