Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38511

Re: Coercing one object to type of another

References <90002ad8-06fe-42d3-a463-a43c0b2401aa@googlegroups.com> <mailman.1534.1360406617.2939.python-list@python.org> <05481ed7-ee0c-4cbd-9490-ada64735cb90@googlegroups.com>
Date 2013-02-09 22:31 +1100
Subject Re: Coercing one object to type of another
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1542.1360409469.2939.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Feb 9, 2013 at 10:23 PM, Vijay Shanker <deontics@gmail.com> wrote:
> well it will always return me this:
> <type 'str'>
>
> what i want is if i know arg1 is of string type(and it can be of any type, say list, int,float) and arg2 is of any type, how can i convert it to type of arg1,
> if arg1='hello world', type(arg1).__name__ will give me 'str', can i use this to convert my arg2 to this type, w/o resorting to if-elif conditions as there will be too many if-elif-else and it doesn really sounds a great idea !

Oh, okay. Then switch the order of the arguments in what I posted:

def coerce(target,convertme):
    return type(target)(convertme)

You don't need to worry about the actual name of the type. It's
telling you that it's <type 'str'>; that's an actual callable object
(the same as the builtin name str, in this case). You can then call
that to coerce the other argument to that type.

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Coercing one object to type of another Vijay Shanker <deontics@gmail.com> - 2013-02-09 02:29 -0800
  Re: Coercing one object to type of another Chris Angelico <rosuav@gmail.com> - 2013-02-09 21:43 +1100
    Re: Coercing one object to type of another Vijay Shanker <deontics@gmail.com> - 2013-02-09 03:23 -0800
      Re: Coercing one object to type of another Chris Angelico <rosuav@gmail.com> - 2013-02-09 22:31 +1100
    Re: Coercing one object to type of another Vijay Shanker <deontics@gmail.com> - 2013-02-09 03:23 -0800
  Re: Coercing one object to type of another Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-10 08:11 +1100

csiph-web