type(foo) == function ?

Chris Mellon arkanes at gmail.com
Wed Nov 29 16:27:01 EST 2006


On 11/29/06, Tom Plunket <tomas at fancy.org> wrote:
> Erik Max Francis wrote:
>
> > In dynamically-typed languages in general, explicit typechecks are not
> > a good idea, since they often preclude user-defined objects from being
> > used.  Instead, try performing the call and catch the resulting
> > TypeError:
>
> Good point, although I need to figure out if the thing can be called
> without calling it, so I can build an appropriate UI.  Basically I
> expect three types of things in the 'value' field of the top-level
> dictionary.  The three sorts of things that I will deal with in the UI
> are callable things (e.g. functions, for which Chris Mellon reminds me
> about callable()), mappings (e.g. dictionaries, used similarly to the
> top-level one), and sequences of strings.
>
> So I think callable() works for me in the general case, but now
> trawling the documentation in that area I'm not sure how I can tell if
> something is a mapping or if it's a sequence.
>
> The gist of the UI generation may be envisioned as:
>
> key is the name that gets assigned to the control.
> value indicates that the UI element is a:
>    "group box" if the value is a mapping
>    series of "radio buttons" if the value is a sequence of strings
>    "check box" if the value is a function
>
> ...I've still gotta figure out the exact API, this is for a plugin
> sort of system that'll be used by the manually-driven version of the
> build process and this data is explicitly to build the UI for the
> various tools that are available.
>

Since a sequence can be viewed as a special case of a mapping (a dict
with integer keys) I don't think there's a good general case way to
tell.

You could try indexing it with a string, a sequence will throw a
TypeError, while a mapping will give you a result or a KeyError.

You could also just rely on isinstance() checks.

> thanks,
> -tom!
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list