Python scopes: setting a class attribute

Status
Not open for further replies.

gloucester

Ars Scholae Palatinae
996
In Python 2.x, names outside the local scope are wholly inaccessible except by passing them in, unless they happen to be in the global scope.

I have a class that has a couple of read-only/constant attributes that are used as parameters in a complex calculation of another class attribute. Instances of Foo should all have the same value of this calculated attribute. So I have something like this:
Code:
class Foo(object):
    spam = 1
    eggs = 2

    def make_bacon(x, y, f):
        dead_pig = f(x, y)
        # do more stuff with dead_pig to make it into bacon
        return bacon

    def slaughter_the_pig(x, y)
        # blah, blah
        return dead_pig

    bacon = make_bacon(spam, eggs, slaughter_the_pig)
(Don't ask me why I need spam and eggs to slaughter a pig.)

In other words, if I have a complex attribute bacon whose calculation relies on helper functions and other attributes, I have to pass everything in. That isn't the end of the world, but this is a case where I would be tempted to use the nonlocal keyword in Python 3.x. (I'm using Python 2.7 here.)

I tried a few different ways of coding this and ended up somewhat confused. First, I thought this could also be done by making make_bacon a class method like so:
Code:
# inside Foo

@classmethod
def make_bacon(cls):
    dead_pig = cls.slaughter_pig(cls.spam, cls.eggs)
    # do more stuff with dead_pig to make it into bacon
    return bacon

bacon = Foo.make_bacon()
But apparently that doesn't work. It raise a NameError on the call to Foo.make_bacon(), saying Foo is not defined. (Also, doing bacon = make_bacon instead raises a TypeError, with the message "'classmethod' is not callable". I thought I knew why that doesn't work—no class is passed in—but the error message makes me doubt my understanding of what's going on there, too. ...)

Likewise, referencing Foo directly inside the helper methods, e.g.,
Code:
# inside Foo

def make_bacon():
    dead_pig = Foo.slaughter_pig(Foo.spam, Foo.eggs)
    # blah blah blah
    return bacon
also raises a NameError. Which seems quite odd because Foo is indeed in the global scope and should be accessible. I have some examples sitting in front of me that do just this, but I get a NameError. Color me confused.

And of course I could just use the ordinary model of using instance attributes and calculate bacon each time an instance is initialized, but that's precisely what I want to avoid—calculating bacon is expensive, and anyway it should be the same for every instance.

Another alternative is to put all of this junk in the module's base scope and do the calculation there, but that also seems like an ugly solution.

Anyone care to elucidate what's going wrong in the classmethod and direct-Foo-call code? How would you code this?

Edit: rewritten to focus on the real issue
 

lostnihilist

Ars Scholae Palatinae
1,436
I'm not 100% sure what you are trying to achieve. I know you've got a serious error in the signatures of your methods: no self!

If I understand you correctly, you've got some class level constants that you want shared. And then, from this, you have a derived value that you also want to be shared across all instances. There are two approaches I can think of for this. One is to initialize the constant on class creation, the other on the first instant creation. To initialize on class creation, do something like this:

Code:
def calc_expensive_const(x,y):
    return x+y

class Foo(object):
    const1 = 1
    const2 = 2
    expensive_const = calc_expensive_const(const1, const2)

And the behavior:
Code:
>>> print Foo.expensive_const
3
>>> f = Foo()
>>> f.expensive_const
3

And for calculating at first instantiation:
Code:
class Foo1(object):
    const1 = 1
    const2 = 2
    expensive_const = None
    @staticmethod
    def calc_exp_const(x,y):
        return x+y
    def __init__(self):
        if Foo1.expensive_const is None:
            Foo1.expensive_const = self.calc_exp_const(Foo1.const1, Foo1.const2)

and its behavior:

Code:
>>> print Foo1.expensive_const
None
>>> f = Foo1()
>>> print Foo1.expensive_const
3
>>> print f.expensive_const
3

Now, the first approach clutters the name space a bit, but only with one function. I used a staticmethod in the second approach just to display how to use it along side a normal instance method (__init__ with self). Notice that if you need to access the calculated value before instantiating a Foo1 instance, you will get None instead of the hoped for value. OTOH, leaving an expensive calculation in a class definition could make imports more expensive than you might like.

I did try to try to make it so that the calculate function there was a static method in the first approach, but I ran into an interesting problem there:

Code:
>>> class Foo2(object):
...     const1 = 1
...     const2 = 2
...     @staticmethod
...     def calc_expensive_const(x,y):
...         return x+y
...     expensive_const = calc_expensive_const(const1, const2)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in Foo2
TypeError: 'staticmethod' object is not callable

If anyone has insight on what is going on with this last situation, I would appreciate it.
 

gloucester

Ars Scholae Palatinae
996
Thanks for the replies, guys.

lostnihilist":2yww0vsl said:
I'm not 100% sure what you are trying to achieve. I know you've got a serious error in the signatures of your methods: no self!
The point is that I don't need or want these methods to be related in any way to class instances. The methods don't have self arguments because I'm trying to come up with something in which everything happens on class creation and nothing happens on instantiation or from an existing instance.

lostnihilist":2yww0vsl said:
To initialize on class creation, do something like this:

Code:
def calc_expensive_const(x,y):
    return x+y

class Foo(object):
    const1 = 1
    const2 = 2
    expensive_const = calc_expensive_const(const1, const2)
... Now, [this] approach clutters the name space a bit, but only with one function.
Yes, this is what I meant when I wrote

Another alternative is to put all of this junk in the module's base scope and do the calculation there, but that also seems like an ugly solution.
It's not a big deal in the examples we're talking about, but it gets worse as there are more and more helper functions needed. Mostly it just bothers me that code that rightfully belongs to the class can't exist inside the class's scope.

lostnihilist":2yww0vsl said:
And for calculating at first instantiation:
Code:
class Foo1(object):
    const1 = 1
    const2 = 2
    expensive_const = None
    @staticmethod
    def calc_exp_const(x,y):
        return x+y
    def __init__(self):
        if Foo1.expensive_const is None:
            Foo1.expensive_const = self.calc_exp_const(Foo1.const1, Foo1.const2)
That's a decent solution to that part of the problem, but it ignores the real sticking point—how do you call helper functions from within calc_exp_const? You can't, except by (again) dumping them into the module's base scope or by passing them in as arguments.

lostnihilist":2yww0vsl said:
Notice that if you need to access the calculated value before instantiating a Foo1 instance, you will get None instead of the hoped for value. OTOH, leaving an expensive calculation in a class definition could make imports more expensive than you might like.
It what way does it make imports more expensive? If you have to run the code, you have to access it at some point. How can you make it less expensive than setting it up to be run exactly once? (Which is almost the whole point to needing to do something like this.)

lostnihilist":2yww0vsl said:
I did try to try to make it so that the calculate function there was a static method in the first approach, but I ran into an interesting problem there:

Code:
>>> class Foo2(object):
...     const1 = 1
...     const2 = 2
...     @staticmethod
...     def calc_expensive_const(x,y):
...         return x+y
...     expensive_const = calc_expensive_const(const1, const2)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in Foo2
TypeError: 'staticmethod' object is not callable

If anyone has insight on what is going on with this last situation, I would appreciate it.
I had an example like that in my post before I edited it. This happens with both classmethod- and staticmethod-decorated methods if you fail to pass them a class either directly by doing Foo2.calc_expensive_const(x,y) or via an instance, e.g., Foo2().calc_expensive_const(x,y). The "object is not callable" error message is pretty opaque, but the fundamental problem is that it's looking for a class somewhere and doesn't get one.

So in the last line of your example, the seemingly correct solution is to write Foo2.expensive_const = calc_expensive_const(const1, const2)—but that raises a NameError, as I described in the OP. This is very confusing because Foo2 is absolutely in the global namespace. If you have any doubt, check globals() and there it is.

So it is apparently impossible to call a staticmethod- or classmethod-decorated function from inside the class, for reasons I do not entirely understand. You can get your last example to work simply by de-decorating it, though of course it will then break if you call it from outside the class because it will expect an instance as its implied first argument. In my case, that still seems like the best solution—these functions should never be used outside the logic in the class itself, so just name them with a leading underscore and be done with it.

But that's why I wanted to see what you people had to say. ... And if anyone can figure out the NameError, please do tell.
 

gloucester

Ars Scholae Palatinae
996
Oh. I thought I had tested this already, but apparently the NameError is thrown because the classname is not added to the global namespace until after the whole class is read-in/created. (That is, it is not in globals() at that point, contrary to what I wrote above.) So you can't call a class from within itself.

And I guess that's the whole point. You can't access the names in a class from scopes nested inside the class. That strikes me as a bit odd, but oh well. I guess that's what nonlocal is for in Python 3.
 

Alamout

Ars Legatus Legionis
27,285
^ I was about to test that, because it didn't sound right to me when you said it earlier. I guess I don't have to, now.

It sounds like you should split this class into its own module, possibly with a class inside of that to deal with the instances (assuming you'll have some eventually). I don't see why you want to store all these things inside the class so badly.
 

agifford

Ars Tribunus Militum
2,142
If you are referring to:

Code:
class textfile: 
... 
  def totfiles(): 
    print "the total number of text files is", textfile.ntfiles 
  totfiles = staticmethod(totfiles) 
... 
# here we are in "main" 
... 
textfile.totfiles()

Then no, nothing funny is going on, and its not doing what you are trying to do.

textfile.ntfiles & totfiles are not being used until after the class is defined. You are trying to use them during class definition time, big difference.

You could make your variable(bacon) a static method, so that the first time its accessed it calculates the value, instead of at class def time.

Code:
class Foo(object):
    spam = 1
    eggs = 2

    make_bacon = lambda x,y,f : f(x,y)
    slaughter_the_pig = lambda x,y : x+y

    bacon = make_bacon(spam, eggs, slaughter_the_pig)

works too, since you don't ever reference the not yet created Foo, or staticmethods for the class
 

gloucester

Ars Scholae Palatinae
996
agifford":1axuzgo1 said:
If you are referring to:

Code:
class textfile: 
... 
  def totfiles(): 
    print "the total number of text files is", textfile.ntfiles 
  totfiles = staticmethod(totfiles) 
... 
# here we are in "main" 
... 
textfile.totfiles()

Then no, nothing funny is going on, and its not doing what you are trying to do.

textfile.ntfiles & totfiles are not being used until after the class is defined. You are trying to use them during class definition time, big difference.
Oh, right. I noticed the textfile.ntfiles reference inside totfiles and missed that the call to totfiles was in __main__. ...

agifford":1axuzgo1 said:
You could make your variable(bacon) a static method, so that the first time its accessed it calculates the value, instead of at class def time.

Code:
class Foo(object):
    spam = 1
    eggs = 2

    make_bacon = lambda x,y,f : f(x,y)
    slaughter_the_pig = lambda x,y : x+y

    bacon = make_bacon(spam, eggs, slaughter_the_pig)

works too, since you don't ever reference the not yet created Foo, or staticmethods for the class
Right, and of course that works with named functions as well. Passing everything in as arguments always works.

I guess most of my confusion stemmed from a mistaken conception of how/when namespaces are created, and what's included in the namespace of different objects. I did not expect functions' and classes' namespaces to work differently. This is what I mean:

Code:
# functions' inner namespaces inherit the outer namespace:
def foo_func():
    spam = 1
    eggs = 2
    
    def make_bacon():
        print spam + eggs # no problem here
    
    return make_bacon()

foo_func() # prints 3

# but that doesn't work with classes:
class Foo(object):
    spam = 1
    eggs = 2
    
    def make_bacon():
        print spam + eggs # NameError
    
    bacon = make_bacon()

Foo.bacon()

That just seems oddly inconsistent to me. Additionally, although on the one hand it's perfectly reasonable for the interpreter to throw a NameError if you try to call Foo.spam inside the class Foo—since the class object hasn't been created yet—on the other hand, when you write Foo.spam, you're not refering to Foo the object. You're refering to Foo only as the namespace containing spam, which has already been created. And Foo is at that point already in the symbol table, so there's really no reason you shouldn't be able to refer to Foo.spam before Foo has been created. In fact, that's exactly what happens (obviously) at the module level, so this really is yet another instance of some objects' namespaces behaving differently than others.

Seems to me that things would be simpler and clearer if everything worked the same way—ideally, in my opinion, in dot notation everything to the left of the final dot should simply be a namespace look-up and only the name to the right of the final dot need be bound to an object for the reference to be valid.

But, anyway, now I'm just carrying on. Thanks for the help and patience, everyone. Obviously there's no reason I need to do anything this particular way, I'm just trying to wrap my head around how this works, which is not how I had expected.
 

gloucester

Ars Scholae Palatinae
996
Yes, you're right. As with most of my threads here, this is not really about "how do I shove this square peg into this round hole", though I understand that it may seem like that; rather, it's about "here's something a bit unexpected, let me see what better programmers than me have to say about it and maybe I'll learn something about the ins and outs of the language." And I have indeed learned something about Python's scopes.

Implementing things like this in the future, I will just pass everything in as arguments in the simple cases (which you will note is the very first method I presented in the OP), and put the logic in __main__ in complex cases (which I also mentioned as a solution in the OP).
 
Status
Not open for further replies.