detecting variable types

Discussion in 'Python' started by Jay, Sep 22, 2004.

  1. Jay

    Jay Guest

    I'm sure this is a really dumb question, but how do you detect a variable
    type in Python?

    For example, I want to know if the variable "a" is a list of strings or a
    single string. How do I do this?
    Jay, Sep 22, 2004
    #1
    1. Advertising

  2. Jay

    Peter Hansen Guest

    Jay wrote:
    > I'm sure this is a really dumb question, but how do you detect a variable
    > type in Python?
    >
    > For example, I want to know if the variable "a" is a list of strings or a
    > single string. How do I do this?


    Use the builtin function "type()", but note the following:

    1. Variables don't actually have types in Python (and they're usually
    called "names" in Python, for various reasons), but the data they are
    currently bound to does have a type and that's what type() returns.
    Often the distinction won't matter to you...

    2. Most of the time people trying to do what you are probably trying
    to do are going about things the wrong way, often from experience
    with other languages. Lots of Python folks would be happy to introduce
    you to "better" ways to do things, if you'll explain the use case
    and tell us what you're actually trying to accomplish. (Of course,
    using "type()" will work, but it's rarely considered the best
    approach in the Python community.)

    -Peter
    Peter Hansen, Sep 22, 2004
    #2
    1. Advertising

  3. Jay

    Chris Green Guest

    "Jay" <> writes:

    > I'm sure this is a really dumb question, but how do you detect a variable
    > type in Python?
    >
    > For example, I want to know if the variable "a" is a list of strings or a
    > single string. How do I do this?


    >>> type("a")

    <type 'str'>
    >>> type(1)

    <type 'int'>

    you should look at the types module as well

    >>> type("a") == types.StringType

    True
    --
    Chris Green <>
    This is my signature. There are many like it but this one is mine.
    Chris Green, Sep 22, 2004
    #3
  4. Jay

    Jay Guest

    Thanks, Peter.

    Here's what I'm trying to do:

    I have a function like this:

    def func(**params):

    # if params[key1] is a single string
    # do something with params[key1]

    # if params[key1] is a list of strings
    for val in params[key1]:
    # do something

    Could you suggest a better way to do this without detecting the type?


    Jay.


    "Peter Hansen" <> wrote in message
    news:...
    > Jay wrote:
    > > I'm sure this is a really dumb question, but how do you detect a

    variable
    > > type in Python?
    > >
    > > For example, I want to know if the variable "a" is a list of strings or

    a
    > > single string. How do I do this?

    >
    > Use the builtin function "type()", but note the following:
    >
    > 1. Variables don't actually have types in Python (and they're usually
    > called "names" in Python, for various reasons), but the data they are
    > currently bound to does have a type and that's what type() returns.
    > Often the distinction won't matter to you...
    >
    > 2. Most of the time people trying to do what you are probably trying
    > to do are going about things the wrong way, often from experience
    > with other languages. Lots of Python folks would be happy to introduce
    > you to "better" ways to do things, if you'll explain the use case
    > and tell us what you're actually trying to accomplish. (Of course,
    > using "type()" will work, but it's rarely considered the best
    > approach in the Python community.)
    >
    > -Peter
    Jay, Sep 22, 2004
    #4
  5. Jay

    djw Guest

    Jay wrote:

    > Thanks, Peter.
    >
    > Here's what I'm trying to do:
    >
    > I have a function like this:
    >
    > def func(**params):
    >
    > # if params[key1] is a single string
    > # do something with params[key1]
    >
    > # if params[key1] is a list of strings
    > for val in params[key1]:
    > # do something
    >
    > Could you suggest a better way to do this without detecting the type?
    >
    >
    > Jay.
    >
    >
    > "Peter Hansen" <> wrote in message
    > news:...
    >> Jay wrote:
    >> > I'm sure this is a really dumb question, but how do you detect a

    > variable
    >> > type in Python?
    >> >
    >> > For example, I want to know if the variable "a" is a list of strings or

    > a
    >> > single string. How do I do this?

    >>
    >> Use the builtin function "type()", but note the following:
    >>
    >> 1. Variables don't actually have types in Python (and they're usually
    >> called "names" in Python, for various reasons), but the data they are
    >> currently bound to does have a type and that's what type() returns.
    >> Often the distinction won't matter to you...
    >>
    >> 2. Most of the time people trying to do what you are probably trying
    >> to do are going about things the wrong way, often from experience
    >> with other languages. Lots of Python folks would be happy to introduce
    >> you to "better" ways to do things, if you'll explain the use case
    >> and tell us what you're actually trying to accomplish. (Of course,
    >> using "type()" will work, but it's rarely considered the best
    >> approach in the Python community.)
    >>
    >> -Peter



    One obvious way, in this case is to always pass in a list of strings. A
    single string would be passed in as a list with a single string item in it.

    def func( stringlist ):
    for s in stringlist:
    #do something with s

    func( [ "single string" ] )
    func( [ "more", "than", "one", "string" ] )

    Other than that, if the functions are really doing something very different
    given different parameter types, then I would make separate functions.

    -Don
    djw, Sep 22, 2004
    #5
  6. Jay

    John Roth Guest

    "Jay" <> wrote in message
    news:ciskpq$7f2$...
    > Thanks, Peter.
    >
    > Here's what I'm trying to do:
    >
    > I have a function like this:
    >
    > def func(**params):
    >
    > # if params[key1] is a single string
    > # do something with params[key1]
    >
    > # if params[key1] is a list of strings
    > for val in params[key1]:
    > # do something
    >
    > Could you suggest a better way to do this without detecting the type?


    I'd strongly suggest making the value of "key1" a list in
    all cases, including the case where there is no value:
    that is, an empty list.

    It makes your processing logic a lot simpler, and even if
    you can't make the caller do it that way, the function/method
    to preprocess is fairly simple (and also takes care of the
    "key not found" case.)

    John Roth
    >
    >
    > Jay.
    >
    >
    > "Peter Hansen" <> wrote in message
    > news:...
    >> Jay wrote:
    >> > I'm sure this is a really dumb question, but how do you detect a

    > variable
    >> > type in Python?
    >> >
    >> > For example, I want to know if the variable "a" is a list of strings or

    > a
    >> > single string. How do I do this?

    >>
    >> Use the builtin function "type()", but note the following:
    >>
    >> 1. Variables don't actually have types in Python (and they're usually
    >> called "names" in Python, for various reasons), but the data they are
    >> currently bound to does have a type and that's what type() returns.
    >> Often the distinction won't matter to you...
    >>
    >> 2. Most of the time people trying to do what you are probably trying
    >> to do are going about things the wrong way, often from experience
    >> with other languages. Lots of Python folks would be happy to introduce
    >> you to "better" ways to do things, if you'll explain the use case
    >> and tell us what you're actually trying to accomplish. (Of course,
    >> using "type()" will work, but it's rarely considered the best
    >> approach in the Python community.)
    >>
    >> -Peter

    >
    >
    John Roth, Sep 22, 2004
    #6
  7. Jay wrote:

    > def func(**params):
    >
    > # if params[key1] is a single string
    > # do something with params[key1]
    >
    > # if params[key1] is a list of strings
    > for val in params[key1]:
    > # do something
    >
    > Could you suggest a better way to do this without detecting the type?


    def func_for_string(astring):
    pass

    def func_for_a_list_of_strings(alist):
    pass


    Also, top posting is evil. See
    http://www.cs.tut.fi/~jkorpela/usenet/brox.html
    Tuure Laurinolli, Sep 22, 2004
    #7
  8. "Jay" <> wrote in message
    news:ciskpq$7f2$...

    > Here's what I'm trying to do:
    >
    > I have a function like this:
    >
    > def func(**params):
    >
    > # if params[key1] is a single string
    > # do something with params[key1]
    >
    > # if params[key1] is a list of strings
    > for val in params[key1]:
    > # do something
    >
    > Could you suggest a better way to do this without detecting the type?


    I don't see anything particularly wrong with detecting the type this way:

    if isinstance(params[key1], list):
    for val in params[key1]:
    # do something
    else:
    # do something with params[key1]

    Of course that won't work for other kinds of sequences, but if that's what
    you want, then that's what you want.
    Andrew Koenig, Sep 22, 2004
    #8
  9. On 2004-09-22, Andrew Koenig <> wrote:
    > "Jay" <> wrote in message
    > news:ciskpq$7f2$...
    >
    >> Here's what I'm trying to do:
    >>
    >> I have a function like this:
    >>
    >> def func(**params):
    >>
    >> # if params[key1] is a single string
    >> # do something with params[key1]
    >>
    >> # if params[key1] is a list of strings
    >> for val in params[key1]:
    >> # do something
    >>
    >> Could you suggest a better way to do this without detecting the type?

    >
    > I don't see anything particularly wrong with detecting the type this way:
    >
    > if isinstance(params[key1], list):
    > for val in params[key1]:
    > # do something
    > else:
    > # do something with params[key1]
    >
    > Of course that won't work for other kinds of sequences, but if that's what
    > you want, then that's what you want.


    When I write functions that accept either a list or a single
    object, I usually "normalize" the paramter into a list and then
    the rest of the function just operates on lists:

    if not isinstance(myParameter,list):
    myParameter = [myParameter]

    [...]

    for p in myParameter:
    <do whatever>

    [...]

    --
    Grant Edwards grante Yow! Is this where people
    at are HOT and NICE and they
    visi.com give you TOAST for FREE??
    Grant Edwards, Sep 22, 2004
    #9
  10. On Wed, 22 Sep 2004 15:45:55 -0400, "Jay" <> wrote:

    >Thanks, Peter.

    Please don't top-post, ok? Notice what it does to the order
    of your comments and mine vs Peters'. Insert your comments below
    quoted material it refers to, then order can be preserved through
    several generations. Stacking wholes monolithically preserves order
    too, but it gets harder to indicate where in the following monoliths
    your top-posted comments apply.

    >
    >Here's what I'm trying to do:
    >
    >I have a function like this:
    >
    >def func(**params):
    >
    > # if params[key1] is a single string
    > # do something with params[key1]
    >
    > # if params[key1] is a list of strings
    > for val in params[key1]:
    > # do something
    >
    >Could you suggest a better way to do this without detecting the type?
    >

    That particular distinction is extra nasty because strings are also iterable.

    One trouble with type(arg)==list or type(arg)==str is that if your calling
    program wants to pass a list or str subtype later, you will have to change
    your func code to detect the new type, even though it behaves the same.

    So you usually better off with an isinstance(arg, str) than a type(arg)==str test.
    Notice,

    >>> class S(str): pass

    ...
    >>> s=S('hello')
    >>>
    >>> s

    'hello'
    >>> type('hello')

    <type 'str'>
    >>> type(s)

    <class '__main__.S'>
    >>> isinstance('hello', str)

    True
    >>> isinstance(s, str)

    True

    IOW,
    >>> type('hello')==str

    True
    >>> type(s)==str

    False

    Sometimes you do actually need that distinction though.

    >
    >Jay.
    >
    >
    >"Peter Hansen" <> wrote in message
    >news:...
    >> Jay wrote:
    >> > I'm sure this is a really dumb question, but how do you detect a

    >variable
    >> > type in Python?
    >> >
    >> > For example, I want to know if the variable "a" is a list of strings or

    >a
    >> > single string. How do I do this?

    >>
    >> Use the builtin function "type()", but note the following:
    >>
    >> 1. Variables don't actually have types in Python (and they're usually
    >> called "names" in Python, for various reasons), but the data they are
    >> currently bound to does have a type and that's what type() returns.
    >> Often the distinction won't matter to you...
    >>
    >> 2. Most of the time people trying to do what you are probably trying
    >> to do are going about things the wrong way, often from experience
    >> with other languages. Lots of Python folks would be happy to introduce
    >> you to "better" ways to do things, if you'll explain the use case
    >> and tell us what you're actually trying to accomplish. (Of course,
    >> using "type()" will work, but it's rarely considered the best
    >> approach in the Python community.)
    >>
    >> -Peter

    >
    >


    Regards,
    Bengt Richter
    Bengt Richter, Sep 22, 2004
    #10
  11. Jay

    Byron Guest

    Hi Jay,

    You can detect the type of a variable by using the "types" module that
    comes with Python. Here is how to use it:


    >>> import types
    >>> name = "Steven"
    >>> if type(name) is types.StringType:
    print "Yes, name is a string."


    Hope this helps,

    Byron
    ---


    Jay wrote:
    > I'm sure this is a really dumb question, but how do you detect a variable
    > type in Python?
    >
    > For example, I want to know if the variable "a" is a list of strings or a
    > single string. How do I do this?
    >
    >
    Byron, Sep 22, 2004
    #11
  12. Byron wrote:
    > Hi Jay,
    >
    > You can detect the type of a variable by using the "types" module that
    > comes with Python. Here is how to use it:
    >
    >
    > >>> import types
    > >>> name = "Steven"
    > >>> if type(name) is types.StringType:

    > print "Yes, name is a string."
    >
    >
    > Hope this helps,
    >
    > Byron
    > ---
    >
    >
    > Jay wrote:
    >
    >> I'm sure this is a really dumb question, but how do you detect a variable
    >> type in Python?
    >>
    >> For example, I want to know if the variable "a" is a list of strings or a
    >> single string. How do I do this?
    >>
    >>


    If you must switch on the type, use something like:

    ...
    if isinstance(vbl, (string, unicode)):
    vbl = [vbl]
    for element in vbl:
    ...

    There are many more kinds of iterables than kinds of strings,
    and you'll get fewer surprises with the above.

    -Scott David Daniels
    Scott David Daniels, Sep 22, 2004
    #12
  13. Andrew Koenig <> wrote:
    ...
    > I don't see anything particularly wrong with detecting the type this way:
    >
    > if isinstance(params[key1], list):


    Better than checking type(...), but then, a lesser evil need not be
    'right'.

    > Of course that won't work for other kinds of sequences, but if that's what
    > you want, then that's what you want.


    Sometimes people want what's not best for them, and sometimes they
    believe they want something, but really don't. If somebody asks me
    about how best to shoot his own foot, I may perhaps suggest weapon types
    and suitable ammunition, but often I'd add some note about the problems
    that often result by shooting one's own foot, even with the most
    suitable choice of ammunition and weapon. ((Come on -- if somebody
    asked __in a C++ group__ how best to code the equivalent of...:

    if(is_circle(x)) draw_circle(x);
    else if(is_square(x)) draw_square(x);
    ...
    would you just mention how dynamic_cast may be used for the purpose,
    without one word as to how a polymorphic x.draw() is better...?-))

    Nevertheless, singling out _strings_ from other kinds of sequences and
    iterables IS unfortunately needed sometimes. That's why built-in type
    basestring exists: for the sole reason of allowing a typetest of the
    form "if isinstance(whatever, basestring):...". Once strings (byte and
    unicode kinds) are out of the way, all other sequences and iterables can
    often be treated uniformly and polymorphically with a for loop or
    whatever. A frequent idiom:

    if isinstance(whatever, basestring):
    whatever = [whatever]
    try: whatever = iter(whatever)
    except TypeError: whatever = iter([whatever])
    for item in whatever:
    ...

    this deals sensibly with being passed any iterable (singling out strings
    as scalars even though they're iterable) OR any non-iterable (to be
    treated as the equivalent singleton-iterable with that one item only).


    Alex
    Alex Martelli, Sep 22, 2004
    #13
  14. Scott David Daniels <> wrote:
    ...
    > if isinstance(vbl, (string, unicode)):


    Nope! Use isinstance(vbl, basestring) instead. basestring exists for
    that one and only reason... besides str (not 'string') and unicode, any
    user-coded type that _wants_ to be "treated as a string for all intents
    and purposes" may choose to inherit from basestring instead of object
    (it's supposed to get no effect whatsoever from that _except_ from code
    that does this specific kind of typechecking specifically).


    Alex
    Alex Martelli, Sep 23, 2004
    #14
  15. Why subclass Borg ?

    On page 208 in the cookbook Alex seems to say that the Borg class
    should be subclassed. I don't see the necessity.
    Just take the original four-lined Borg(), give it a suitable name,
    maybe add some arguments, add oher methods, and instantiate it.
    Or am I missing something again ?
    egbert
    --
    Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
    ========================================================================
    Egbert Bouwman, Sep 25, 2004
    #15
  16. Re: Why subclass Borg ?

    Egbert Bouwman <> wrote:

    > On page 208 in the cookbook Alex seems to say that the Borg class
    > should be subclassed. I don't see the necessity.
    > Just take the original four-lined Borg(), give it a suitable name,
    > maybe add some arguments, add oher methods, and instantiate it.
    > Or am I missing something again ?


    If you need two classes with "singleton-like behavior", implementing
    them as subclasses of Borg is preferable to "copy and paste ``reuse''"
    for much the same reason real reuse is always preferable to c&p reuse,
    whenever feasible. Should there ever be any useful maintenance to Borg
    (e.g., make it a newstyle class, optimize it in some other way,
    whatever!), if you have reused it properly you're in clover; if you have
    copied and pasted, you're not. As usual, there are _no_ compensating
    advantages for "copy and paste ``so-called reuse''" whatsoever.

    _Once, and ONLY once_. ANY TIME you have the same functionality coded
    twice, in two places, in two copies, that should raise your hackles.
    Train yourself to feel DISGUST at such cases, and remove them
    immediately whenever you observe them, in favour of a "once and only
    once" occurrence of the functionality, reused in two or more places in
    the proper ways (function calls, class instantiation, inheritance,
    whatever). You'll be MUCH happier as a result of such a stance,
    throughout your programming career.


    Alex
    Alex Martelli, Sep 25, 2004
    #16
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris

    Detecting document types

    Chris, Nov 24, 2003, in forum: Java
    Replies:
    0
    Views:
    333
    Chris
    Nov 24, 2003
  2. Lasse Skyum

    detecting basic types

    Lasse Skyum, Dec 22, 2003, in forum: C++
    Replies:
    6
    Views:
    444
    Lasse Skyum
    Dec 24, 2003
  3. Replies:
    1
    Views:
    257
    Roedy Green
    May 7, 2007
  4. Replies:
    1
    Views:
    3,439
    Roedy Green
    Sep 23, 2007
  5. RobG

    Detecting support for event types

    RobG, Aug 15, 2008, in forum: Javascript
    Replies:
    15
    Views:
    187
    dhtml
    Aug 22, 2008
Loading...

Share This Page