I have written some code in Python involving type checks, for safety, but one of them is failing consistently in one spot, but also working in nearly the same spot.
This check works in the Point class:
def __repr__(self) :
print('we be an instance: {}'.format(isinstance(self,Point)))
return "(point: state:{}; conns:{})".format(Conversion.getStateAsStr(self), connections[self])
and prints out we be an instance: true
successfully.
However, the method Conversion.getStateAsStr
is reporting that the given object is not a Point
:
def getStateAsStr(p) :
if not isinstance(p, Point) :
raise TypeError("Non-point")
if p.state : # state is a var in Point
return "On"
return "Off"
import pointsys
from pointsys import Point
A TypeError
is raised consistently when trying to repr()
or str()
a Point
. What is going on, and how do I fix it?
Edit: The entire Conversion.py currently consists of the above getStateAsStr snippet. The imports are at the bottom to prevent errors with cyclic imports.
VERY IMPORTANT: If run from Conversion.py, it works like a charm. Running from the pointsys file produces the TypeError from getStateAsStr
Here is the entire pointsys.py file with the Point
class:
connections = {}
def writeConnection(point, connList) :
connections[point] = connList
def addConnection(point, point2) :
if point2 not in connections[point] :
connections[point].append(point2)
else :
print("Skipping point {}".format(point2))
def remConnection(point, point2) :
connections[point].remove(point2)
class Point():
def __init__(self) :
self.state = Off
writeConnection(self, [])
def __repr__(self) :
print('we be an instance: {}'.format(isinstance(self,Point)))
return "(point: state:{}; conns:{})".format(Conversion.getStateAsStr(self), connections[self])
"""
Makes or removes a connection between this point and p2
"""
def markConnection(self, p2, connected) :
if connected :
addConnection(self, p2)
elif not connected :
remConnection(self, p2)
"""
Returns if this point is connected to p2
"""
def isConnected(self, p2) :
return p2 in connections[self]
"""
Sets the state of this point and it's connections
"""
def pushState(self, state) :
self.state = state
for connection in connections[self][:] :
connection.pushState(state)
import Conversion
from State import Off, On, Connected, Unconnected