Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"self" inside plain function?

Tags:

python

I've got a bunch of functions (outside of any class) where I've set attributes on them, like funcname.fields = 'xxx'. I was hoping I could then access these variables from inside the function with self.fields, but of course it tells me:

global name 'self' is not defined

So... what can I do? Is there some magic variable I can access? Like __this__.fields?


A few people have asked "why?". You will probably disagree with my reasoning, but I have a set of functions that all must share the same signature (accept only one argument). For the most part, this one argument is enough to do the required computation. However, in a few limited cases, some additional information is needed. Rather than forcing every function to accept a long list of mostly unused variables, I've decided to just set them on the function so that they can easily be ignored.

Although, it occurs to me now that you could just use **kwargs as the last argument if you don't care about the additional args. Oh well...

Edit: Actually, some of the functions I didn't write, and would rather not modify to accept the extra args. By "passing in" the additional args as attributes, my code can work both with my custom functions that take advantage of the extra args, and with third party code that don't require the extra args.

Thanks for the speedy answers :)

like image 223
mpen Avatar asked Jul 08 '10 20:07

mpen


People also ask

What does self do in a function?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

What is the purpose of self in Python?

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

What is self in Python with example?

The self keyword is used to represent an instance (object) of the given class. In this case, the two Cat objects cat1 and cat2 have their own name and age attributes. If there was no self argument, the same class couldn't hold the information for both these objects.

Why is self not defined?

The “NameError: name 'self' is not defined” error is raised when you forget to specify “self” as a positional argument or when you use “self” in another argument in a list of arguments. You solve this error by making sure that all methods in a function that use “self” include “self” in their list of arguments.


2 Answers

self isn't a keyword in python, its just a normal variable name. When creating instance methods, you can name the first parameter whatever you want, self is just a convention.

You should almost always prefer passing arguments to functions over setting properties for input, but if you must, you can do so using the actual functions name to access variables within it:

def a:
    if a.foo:
        #blah

a.foo = false
a()

see python function attributes - uses and abuses for when this comes in handy. :D

like image 131
Gordon Gustafson Avatar answered Oct 21 '22 14:10

Gordon Gustafson


def foo():
    print(foo.fields)
foo.fields=[1,2,3]

foo()
# [1, 2, 3]

There is nothing wrong with adding attributes to functions. Many memoizers use this to cache results in the function itself.

For example, notice the use of func.cache:

from decorator import decorator
@decorator
def memoize(func, *args, **kw):
    # Author: Michele Simoniato
    # Source: http://pypi.python.org/pypi/decorator
    if not hasattr(func, 'cache'):
        func.cache = {}
    if kw: # frozenset is used to ensure hashability
        key = args, frozenset(kw.iteritems())
    else:
        key = args
    cache = func.cache # attribute added by memoize
    if key in cache:
        return cache[key]
    else:
        cache[key] = result = func(*args, **kw)
        return result
like image 36
unutbu Avatar answered Oct 21 '22 13:10

unutbu