6

I have the following code:

model =  MyModel()
field = model._meta.get_field_by_name('my_field')[0]
my_type = field.get_internal_type
print str(my_type)

This outputs:

<bound method URLField.get_internal_type of <django.db.models.fields.URLField: my_field>>

How can I extract the URLField type from the ubound method output?

7
  • 4
    Why not call the method, that method returns the internal type as a string.. Commented Nov 19, 2013 at 22:55
  • Are you asking the exact same question as here and here, or are you asking something different? It's very hard to tell. If you're asking something different, make the difference clear. If you're asking the same thing, stop asking it over and over. Commented Nov 19, 2013 at 23:04
  • I'm asking something different @abarnert Commented Nov 19, 2013 at 23:05
  • @MartijnPieters what "the" method? Commented Nov 19, 2013 at 23:05
  • 3
    @Atma you're not calling the method here - my_type = field.get_internal_type, do it like this - my_type = field.get_internal_type() Commented Nov 19, 2013 at 23:07

2 Answers 2

11

In Python 2.x, a bound method has three attributes:

  • im_func is the function object.
  • im_class is the class the method comes from.
  • im_self is the self object the method is bound to.

So, just do this:

print my_type.im_self

In Python 3.x, im_func is renamed __func__, im_self is renamed __self__, and im_class is gone.

In 2.7, you can use the 3.x names in place of the 2.x names if you prefer.


The details of this are buried pretty deep in the documentation, but the inspect module docs has a handy table giving you a brief explanation of what the most important special fields in the various built-in types do.

This blog post has more detail, and if you want to know why it works like that, that's mostly documented in a few different posts on Guido's History of Python blog between from March 2009 and June 2010.

Sign up to request clarification or add additional context in comments.

3 Comments

He has the object right there; field, but the specific method, if called, returns a string representing the field type.. This is pretty Django specific, I suspect.
@MartijnPieters: I'm not sure that's what he's asking. He wanted "the URLField type from the bound method". In other words, he wants the actual data behind the <django.db.models.fields.URLField: my_field> in the repr. Which is the im_self.
@abarnert, no, he wants just a return value.. proofs: 1) stackoverflow.com/questions/20081924/…, 2) stackoverflow.com/questions/20083764/…. I really don't understand why he keeps duplicating this..
6

Thanks @Martijn Pieters

The answer is to call the method instead:

my_type = field.get_internal_type()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.