2

I'm very new to python and (coming from Java) am trying to think in a "pythonic" way. I'm having trouble understanding how Django turns a function (or variable) name given in string to the actual function.

Example from Django tutorial: If we give:

list_display = ('question', 'pub_date', 'was_published_recently')

Django reads the function and some related properties from the code:

def was_published_recently(self):
 return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
 was_published_recently.admin_order_field = 'pub_date'
 was_published_recently.boolean = True
 was_published_recently.short_description = 'Published recently?'

So, my question: How does the string get turned into the actual function name?

asked Jan 3, 2013 at 14:31
2
  • 1
    many interpreted languages model objects as associative arrays with strings as keys and the members and functions as values Commented Jan 3, 2013 at 14:45
  • See stackoverflow.com/questions/5488155/… Commented Jan 3, 2013 at 16:09

1 Answer 1

8

Python has numerous ways to turn strings into objects. The most important are:

  • Attribute access with getattr(), allowing you to translate foo.bar into getattr(foo, 'bar').

  • Dictionary access, mapping[key]. Almost anything in Python can be reduced to dictionaries; by default class instances store information in a mapping called __dict__ for example, so instance.__dict__[key] works in many cases. Module namespaces use a mapping like that too.

    The built-in functions vars(), locals() and globals() all return a namespace mapping.

If you are interested in Python introspection, you may want to study the Python datamodel, and take a look at the inspect library as well.

answered Jan 3, 2013 at 16:15
1
  • Thank you. Exactly what I was looking for. I love concise answers :) Commented Jan 4, 2013 at 3:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.