Question

So I'm in the process of making a class in Python that creates a network (with pybrain) using solely the numeric input it's given {just a little process to get my feet wet in Pybrain's API}.

My problem is, I'm rather unfamiliar with how scopes work in classes, and while I basically have the program set up properly, it keeps returning a keyerror.

All the variables needed to be acted upon are created in the init function; the method I'm working on for the class is trying to call upon one of the variables, declared in the init function using the vars()[] method in Python. (you can actually see a portion of the code's...rough draft here: Matching Binary operators in Tuples to Dictionary Items

Anyways, the method is:

    def constructnetwork(self):
    """constructs network using gathered data in __init__"""
       if self.recurrent:
            self.network = pybrain.RecurrentNetwork  
            #add modules/connections here
       elif self.forward:
            self.network = pybrain.FeedForwardNetwork
       else:
            self.network = pybrain.network

       print vars()[self.CONNECT+str(1)]
       print vars()[self.CONNECT+str(2)]
       print self.network

(pardon the bad spacing, it didn't copy and paste over well.) The part that's raising the KeyError is the "print vars()[self.CONNECT+str(1)], which should retreive the value of the variable "Connection1" (self.CONNECT = 'Connection'), but calls a keyerror.

How do I get the variables to transfer over? If you need more information to help just ask, I'm trying to keep the quesiton as short as possible.

Was it helpful?

Solution

vars() returns a reference to the dictionary of local variables. If you used vars() in your __init__ (as the code in the post you linked to suggests), then you just created a local variable in that method, which isn't accessible from anywhere outside that method.

What is it that you think vars() does, and what are you trying to do? I have a hunch that what you want is getattr and setattr, or just a dictionary, and not vars.

Edit: Based on your comment, it sounds like, indeed, you shouldn't use vars. You would be better off, in __init__, doing something like:

 self.connections = {}
 self.connections[1] = "This is connection 1"

then in your method, do:

 self.connections[1]

This is just a vague guess based on your code, though. I can't really tell what you are intending for this "connection". Do you want it to be some data associated with your object?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top