Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What method attributes are used in Django?

Under the documentation for ModelAdmin.list_display it describes a few ways to configure a method/function for usage and display in an admin's list view:

  • admin_order_field (describes which field in the model to use for ordering by the method)
  • allow_tags (allows HTML to be displayed rather than escaped)
  • short_description (sets the label for the column)
  • boolean (determines if the field should be treated a boolean field for display)

It describes them as method attributes.

Addendum

Just found some more method/function attributes, used for template filters:

  • is_safe, used when marking a template filter as safe
  • needs_autoescape, used to deal with autoescaping of data

What other method attributes are there in Django (or even Python)? Or are these really the only cases?

Clarification

Just to be clear, this is what I'm talking about specifically.

In the following code:

class Foo(models.Model):
    name = models.CharField(max_length=100)
    color = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    def is_adult(self):
        return age > 18
    is_adult.boolean = True
    is_adult.short_description = "Over 18?"

    def colored_name(self):
        return '<span style="color: %s">%s</span>' % (self.color, self.name)
    colored_name.allow_tags = True
    colored_name.short_desciption = "Name"
    colored_name.admin_order_field = "name"

The method attributes I'm talking about are is_adult.boolean, is_adult.short_description, colored_name.allow_tags, colored_name.short_description and colored_name.admin_order_field.

If you need any more details, please read the linked documentation.

Addendum #2

Looks like this is partially covered in PEP 232: Function Attributes. The PEP points to a mailing list post that lists other potential use cases for function attributes:

  • I need to associate a Java-style type declaration with a method so that it can be recognized based on its type during Java method dispatch. How would you do that with instances?

  • I need to associate a "grammar rule" with a Python method so that the method is invoked when the parser recognizes a syntactic construct in the input data.

  • I need to associate an IDL declaration with a method so that a COM interface definition can be generated from the source file.

  • I need to associate an XPath "pattern string" with a Python method so that the method can be invoked when a tree walker discovers a particular pattern in an XML DOM.

  • I need to associate multiple forms of documentation with a method. They are optimized for different IDEs, environments or languages.

Here's an implementation that allows method attributes to be callable:

from django.contrib.admin import ModelAdmin
from datetime.datetime import now

class ProfileAdmin(ModelAdmin):

    list_display = ('votes_today',)

    class VotesToday:
        def __call__(self, model_admin, obj):
            today = now().replace(hour=0, minute=0, second=0, microsecond=0)
            return obj.vote_set.filter(created__gte=today)

        @property
        def short_description(self):
            return 'Votes today (%s)' % now().strftime('%B %d')

    @property
    def votes_today(self):
        if not hasattr(self, '__votes_today'):
            self.__votes_today = self.VotesToday()
        return self.__votes_today
like image 382
Jordan Reiter Avatar asked Sep 07 '11 16:09

Jordan Reiter


1 Answers

funny that you should ask about this, I was just a bit surprised by a different use of this in the django documentation earlier today:

def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
# !!! another occurrence of a "method attribute," an attribute
# assigned to a function object.

class PersonAdmin(admin.ModelAdmin):
    list_display = (upper_case_name,)

So, what this means, essentially, is that function definitions are a type of object. A more familiar way of saying this might be:

>>> def myfunc():
...   return "myvalue"

# 'myfunc' is now an object of type 'function' in the local scope. observe:

>>> type(myfunc)
<type: 'function'>

# you can, of course call __call__ on 'myfunc':
>>> myfunc()
"myvalue"
>>> myfunc.__call__()
"myvalue"

# and because 'myfunc' is also a normal object, you can define attributes on it.
myfunc.someattribute = 'somevalue'
myfunc.is_a_function = True
myfunc.takes_args = False

So, your question has a bit to do with the idea that python is "objects all the way down," that is, that everything in python is an object.

Now why is this useful? Suppose you want to collect and use some metadata on a set of functions (or methods) that you're writing:

from operator import attrgetter

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def get_attribute_value(obj, attr):
    return attrgetter(attr)(obj)

add.takes_args = True
add.number_of_args = 2
add.type_of_args = [int, int]
add.uses_black_magic = False

subtract.takes_args = True
subtract.number_of_args = 2
subtract.type_of_args = [int, int]
subtract.uses_black_magic = False

get_attribute_value.takes_args = True
get_attribute_value.number_of_args = 2
get_attribute_value.type_of_args = [object, str]
get_attribute_value.uses_black_magic = True

You could then use these 'method attributes' in a useful way:

def perform_function_checks(function_list):
    for afunc in function_list:
        if getattr(afunc, 'takes_args'):
            print "function '%s' takes args! how unusual!" % (afunc.__name__,)
        if getattr(afunc, 'number_of_args'):
            print "function '%s' takes %s args." % (afunc.__name__, afunc.number_of_args)
        if getattr(afunc, 'type_of_args'):
            print "function '%s' takes %s args: %s" (afunc.__name__, len(afunc.type_of_args), [", and ".join(str(item)) for item in afunc.type_of_args])
        if getattr(afunc, 'uses_black_magic'):
            print "oh no! function '%s' uses black magic!" % (afunc.__name__,)

perform_function_checks([add, subtract, get_attribute_value])

# prints:
# function 'add' takes args! how unusual!
# function 'add' takes 2 args.
# function 'add' takes 2 args: <type 'int'>, and <type 'int'>
# function 'subtract' takes args! how unusual!
# function 'subtract' takes 2 args.
# function 'subtract' takes 2 args: <type 'int'>, and <type 'int'>
# function 'get_attribute_value' takes args! how unusual!
# function 'get_attribute_value' takes 2 args.
# function 'get_attribute_value' takes 2 args: <type 'object'>, and <type 'str'>
# oh no! function 'get_attribute_value' uses black magic!

Now, of course, the above is for illustrative purposes only, if you were actually trying to do this type of introspection on functions and objects you'd probably want to use the 'inspect' module, rather than adding your own bizarro metadata: http://docs.python.org/library/inspect.html

For more information on this topic, I'd recommend this post:

http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html

-- EDIT:

sorry, I didn't address your "implementation that allows method attributes to be callable" under addendum #2.

Your example there is a bit of a red herring in this discussion. What's going on there, is that someone is using the @property decorator to decorate a method to make it look like a property (a.k.a. 'attribute'). Consider this example:

# let's define a simple class
class Foo():
    # and a "normal" attribute
    an_attribute = 'a value'
    # now a method that we'll decorate with the @property decorator
    @property
    def what_kind(self):
        return str(self.__class__.__name__)

# now, instances of our Foo class will have the attribute '.what_kind'.

>>> bar = Foo()

# bar is now an instance of foo.

>>> bar.an_attribute
"a value"

# and finally our decorated method:

>>> bar.what_kind
"Foo"

Note that we did not have to call 'what_kind' above to return the value. I think that all the @property decorator does is automatically call .__call__()

so, what the author of that post is doing is making it look to django that you're just adding a "plain old" attribute to the class, when, in fact, .short_description and .votes_today are actually methods.

Here's more information on the @property decorator/function (which is builtin, BTW, so you don't need to import it): http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/

-- EDIT: fixed a couple of markup problems, and a typo.

like image 73
James Avatar answered Oct 14 '22 00:10

James