tags:

views:

129

answers:

5

If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an __exit__ function.

+2  A: 

Usually method names are disambiguated from global names because you have to prefix self..

So self.set() invokes your class method and set() invokes the global set.

If this doesn't help, perhaps post the code you're having trouble with.

Jon-Eric
+1  A: 

Object attributes are always accessed via a reference, so there is no way for an object attribute to shadow a builtin.

Ignacio Vazquez-Abrams
+2  A: 

You can refer to built-in set as __builtins__.set.

Li0liQ
A: 

If you run the code below you will notice that the set method of the UsesSet class does not obscure the built-in set type.

class UsesSet(object):
    def set(self):
        pass
    def other(self):
        my_set = set([1, 2])
        print type(my_set), my_set

obj = UsesSet()
obj.other()

The code above outputs <type 'set'> set([1, 2]) showing that the set() method of our class has not hidden the built-in set()

If however you have module in which you have defined a function named set like below something different happens:

def set(arg):
    print "This is my own set function"

class UsesSet(object):
    def other(self):
        my_set = set([1, 2])
        print type(my_set), my_set

obj = UsesSet()
obj.other()

The code above outputs:

This is my own set function
<type 'NoneType'> None

So as you can see a module level function with the same name as a built-in hides the built-in.

Tendayi Mawushe
+8  A: 

I think I know what's going on here. Are you doing something like this?

>>> class A(object):
...     def set(self):
...             pass
...     def test(self, x=set):
...             return x
... 
>>> set
<type 'set'>
>>> A().test()
<function set at 0x64270>

This is a subtle problem due to the way methods are defined in classes. It is what allows you to make method aliases so easily, e.g.,

class A(object):
    def some_method(self):
        pass
    some_other_method = some_method

You can either put set at the bottom of your class definition, or you can refer to the builtin set using __builtins__.set.

Dietrich Epp