1 Replies - 487 Views - Last Post: 16 April 2013 - 02:48 PM Rate Topic: -----

#1 Midwest Product  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 74
  • Joined: 05-February 10

Last question: Trouble validating type of object

Posted 16 April 2013 - 02:20 PM

Sorry for bugging you all, but you've been a tremendous help. I've been scouring the Internet for ways to check types of user-defined objects, and have found a lot of ways, but for some reason, I can't get them to work.

Background: I have a class called Project, saved as project.py, located at Project5.prod.project.Project in Eclipse. I have another class called Repository, which is a list that Projects are added to. As a safety precaution, I'm validating all Projects to make sure they are of type Project (so random strings and stuff don't get added).

import Project5.prod.project.Project

class Repository(object):

    def __init__(self):
        self.theContainer = []
    def addProject(self, proj):

        #validation for project
        if(isinstance(proj, project.Project) == False): #error here
            raise ValueError("Repository.addProject: Invalid project.")

To figure out exactly what type my proj is, I added a project to the repository successfully, using both of these methods.

hist = ProjectHistory()
myProject = project.Project(1, 10, 15, 20, 100, 200)
print type(myProject), "type"
hist.addProject(project.Project(2, 10, 15, 20, 100, 200))
print type(project.Project(2, 10, 15, 20, 100, 200)), "type"

Both times, the type is printed to the screen as: <class 'Project5.prod.project.Project'>

However, using the line above, the following error is produced:
if(isinstance(proj, project.Project) == False):

UnboundLocalError: local variable 'project' referenced before assignment

No matter what I enter (Project5.prod.project.Project, project.Project, etc.), the first value is always referenced before assignment. The thing that I don't get is that it isn't a variable...it's supposed to be an object. What's the problem here? I don't get it.

Is This A Good Question/Topic? 0
  • +

Replies To: Last question: Trouble validating type of object

#2 andrewsw  Icon User is offline

  • blow up my boots
  • member icon

Reputation: 6541
  • View blog
  • Posts: 26,484
  • Joined: 12-December 12

Re: Last question: Trouble validating type of object

Posted 16 April 2013 - 02:48 PM

It may require:

    def addProject(self, proj):
        global project

even though you are not (directly) modifying it.

This post has been edited by andrewsw: 16 April 2013 - 02:51 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1