converting a string to a function parameter

Discussion in 'Python' started by koranthala, Mar 13, 2009.

  1. koranthala

    koranthala Guest

    Hi,
    Is it possible to convert a string to a function parameter?
    Ex:
    str = 'True, type=rect, sizes=[3, 4]'
    and I should be able to use it as:
    test(convert(str)) and the behaviour should be same as calling test
    with those values :
    i.e. test(True, type=rect, sizes=[3, 4])

    I tried eval, but it did not work. And any other mechanism I think
    turns out to be creating a full fledged python parser.

    Is there any mechanism with which we can do this straight away?
     
    koranthala, Mar 13, 2009
    #1
    1. Advertising

  2. koranthala

    Chris Rebert Guest

    On Fri, Mar 13, 2009 at 12:52 AM, koranthala <> wrote:
    > Hi,
    >    Is it possible to convert a string to a function parameter?
    > Ex:
    > str = 'True, type=rect, sizes=[3, 4]'
    > and I should be able to use it as:
    > test(convert(str)) and the behaviour should be same as calling test
    > with those values :
    > i.e. test(True, type=rect, sizes=[3, 4])
    >
    > I tried eval, but it did not work. And any other mechanism I think
    > turns out to be creating a full fledged python parser.
    >
    > Is there any mechanism with which we can do this straight away?


    Firstly, don't use `str` as a variable name since it conflicts with
    the name of the builtin type.

    Now here's how to use eval() properly:

    [insert standard 'eval() is EVIL!' warning/lecture here]

    eval("test("+the_str+")")

    or

    eval(test.__name__+"("+the_str+")")

    Cheers,
    Chris

    --
    I have a blog:
    http://blog.rebertia.com
     
    Chris Rebert, Mar 13, 2009
    #2
    1. Advertising

  3. koranthala

    koranthala Guest

    On Mar 13, 1:01 pm, Chris Rebert <> wrote:
    > On Fri, Mar 13, 2009 at 12:52 AM, koranthala <> wrote:
    > > Hi,
    > >    Is it possible to convert a string to a function parameter?
    > > Ex:
    > > str = 'True, type=rect, sizes=[3, 4]'
    > > and I should be able to use it as:
    > > test(convert(str)) and the behaviour should be same as calling test
    > > with those values :
    > > i.e. test(True, type=rect, sizes=[3, 4])

    >
    > > I tried eval, but it did not work. And any other mechanism I think
    > > turns out to be creating a full fledged python parser.

    >
    > > Is there any mechanism with which we can do this straight away?

    >
    > Firstly, don't use `str` as a variable name since it conflicts with
    > the name of the builtin type.
    >
    > Now here's how to use eval() properly:
    >
    > [insert standard 'eval() is EVIL!' warning/lecture here]
    >
    > eval("test("+the_str+")")
    >
    > or
    >
    > eval(test.__name__+"("+the_str+")")
    >
    > Cheers,
    > Chris
    >
    > --
    > I have a blog:http://blog.rebertia.com


    Thank you very much Chris.
    I also thought about the first method a second after I posted this.
    But I never thought about the second method.
    I will heed the warning about the str part.

    Thank you very much again, Chris.
     
    koranthala, Mar 13, 2009
    #3
  4. koranthala

    odeits Guest

    On Mar 13, 12:52 am, koranthala <> wrote:
    > Hi,
    >     Is it possible to convert a string to a function parameter?
    > Ex:
    > str = 'True, type=rect, sizes=[3, 4]'
    > and I should be able to use it as:
    > test(convert(str)) and the behaviour should be same as calling test
    > with those values :
    > i.e. test(True, type=rect, sizes=[3, 4])
    >
    > I tried eval, but it did not work. And any other mechanism I think
    > turns out to be creating a full fledged python parser.
    >
    > Is there any mechanism with which we can do this straight away?


    If the string has all of the names you could parse it into a
    dictionary and pass it as the keyword arguments
     
    odeits, Mar 13, 2009
    #4
  5. koranthala

    Aaron Brady Guest

    On Mar 13, 2:52 am, koranthala <> wrote:
    > Hi,
    >     Is it possible to convert a string to a function parameter?
    > Ex:
    > str = 'True, type=rect, sizes=[3, 4]'
    > and I should be able to use it as:
    > test(convert(str)) and the behaviour should be same as calling test
    > with those values :
    > i.e. test(True, type=rect, sizes=[3, 4])
    >
    > I tried eval, but it did not work. And any other mechanism I think
    > turns out to be creating a full fledged python parser.
    >
    > Is there any mechanism with which we can do this straight away?


    I heard 'pyparsing' was good. ...Not that I've even been to its
    webpage.
     
    Aaron Brady, Mar 13, 2009
    #5
  6. koranthala

    Paul McGuire Guest

    On Mar 13, 11:46 am, Aaron Brady <> wrote:
    > On Mar 13, 2:52 am, koranthala <> wrote:
    >
    > > Hi,
    > >     Is it possible to convert a string to a function parameter?
    > > Ex:
    > > str = 'True, type=rect, sizes=[3, 4]'
    > > and I should be able to use it as:
    > > test(convert(str)) and the behaviour should be same as calling test
    > > with those values :
    > > i.e. test(True, type=rect, sizes=[3, 4])

    >
    > > I tried eval, but it did not work. And any other mechanism I think
    > > turns out to be creating a full fledged python parser.

    >
    > > Is there any mechanism with which we can do this straight away?

    >
    > I heard 'pyparsing' was good.  ...Not that I've even been to its
    > webpage.


    Did someone say 'pyparsing'? :) Here is a first cut (partially lifted
    from a previous post):


    from pyparsing import *

    LPAR,RPAR,LBRACK,RBRACK,EQ,COMMA = map(Suppress,"()[]=,")

    noneLiteral = Literal("None")
    boolLiteral = oneOf("True False")
    integer = Combine(Optional(oneOf("+ -")) + Word(nums)).setName
    ("integer")
    real = Combine(Optional(oneOf("+ -")) + Word(nums) + "." +
    Optional(Word(nums))).setName("real")

    ident = Word(alphas+"_",alphanums+"_")

    listStr = Forward().setName("list")
    tupleStr = Forward().setName("tuple")
    listItem = real | integer | noneLiteral | boolLiteral | \
    quotedString.setParseAction(removeQuotes) | Group(listStr) |
    tupleStr | ident
    listStr << ( LBRACK + Optional(delimitedList(listItem)) + Optional
    (COMMA) + RBRACK )
    tupleStr << (LPAR + Optional(delimitedList(listItem)) + Optional
    (COMMA) + RPAR)

    # parse actions perform parse-time conversions
    noneLiteral.setParseAction(lambda: None)
    boolLiteral.setParseAction(lambda toks: toks[0]=="True")
    integer .setParseAction(lambda toks: int(toks[0]))
    real .setParseAction(lambda toks: float(toks[0]))
    listStr .setParseAction(lambda toks: toks.asList())
    tupleStr .setParseAction(lambda toks: tuple(toks.asList()))

    arg = Group(ident("varname") + EQ + listItem("varvalue")) | listItem


    argstring = 'True, type=rect, sizes=[3, 4,], coords = ([1,2],[3,4])'

    parsedArgs = delimitedList(arg).parseString(argstring)
    args = []
    kwargs = {}
    for a in parsedArgs:
    if isinstance(a,ParseResults):
    if isinstance(a.varvalue,ParseResults):
    val = a.varvalue.asList()
    else:
    val = a.varvalue
    kwargs[a.varname] = val
    else:
    args.append(a)

    print "Args:", args
    print "Kwargs:", kwargs


    Prints:

    Args: [True]
    Kwargs: {'coords': ([1, 2], [3, 4]), 'type': 'rect', 'sizes': [3, 4]}
     
    Paul McGuire, Mar 13, 2009
    #6
  7. koranthala

    Aaron Brady Guest

    On Mar 13, 3:21 pm, Paul McGuire <> wrote:
    > On Mar 13, 11:46 am, Aaron Brady <> wrote:
    >
    >
    >
    > > On Mar 13, 2:52 am, koranthala <> wrote:

    >
    > > > Hi,
    > > >     Is it possible to convert a string to a function parameter?
    > > > Ex:
    > > > str = 'True, type=rect, sizes=[3, 4]'
    > > > and I should be able to use it as:
    > > > test(convert(str)) and the behaviour should be same as calling test
    > > > with those values :
    > > > i.e. test(True, type=rect, sizes=[3, 4])

    >
    > > > I tried eval, but it did not work. And any other mechanism I think
    > > > turns out to be creating a full fledged python parser.

    >
    > > > Is there any mechanism with which we can do this straight away?

    >
    > > I heard 'pyparsing' was good.  ...Not that I've even been to its
    > > webpage.

    >
    > Did someone say 'pyparsing'? :)  Here is a first cut (partially lifted
    > from a previous post):

    snip 40 lines
    > Prints:
    >
    > Args: [True]
    > Kwargs: {'coords': ([1, 2], [3, 4]), 'type': 'rect', 'sizes': [3, 4]}


    Ha, ok, out of my league. It's a bit heavyweight I accede. The OP
    didn't say what s/he knew about his/er data prior, what fault
    tolerance s/he needed, what complexity and nesting of data in the
    string, etc.

    Hmmm..., just thinking. Could the strings come from a python file:
    test1= fargs(True, type=rect, sizes=[3, 4])
    test2= fargs(...)
    ?
     
    Aaron Brady, Mar 13, 2009
    #7
  8. koranthala

    Guest

    Il giorno venerdì 13 marzo 2009 08:52:39 UTC+1, koranthala ha scritto:
    > Hi,
    > Is it possible to convert a string to a function parameter?
    > Ex:
    > str = 'True, type=rect, sizes=[3, 4]'
    > and I should be able to use it as:
    > test(convert(str)) and the behaviour should be same as calling test
    > with those values :
    > i.e. test(True, type=rect, sizes=[3, 4])
    >
    > I tried eval, but it did not work. And any other mechanism I think
    > turns out to be creating a full fledged python parser.
    >
    > Is there any mechanism with which we can do this straight away?


    I need the exact opposite, what is the inverse function?
    example: i pass to a function an argument

    m=[654,54,65]
    def function(m):
    return takethenameof(m)

    and it have to return to me 'm' not [654,54,65] or '[654,54,65]'

    anybody can help?
    i think that when one is talking about a function he have to talk also of the inverse function (also because google have problems searching about this....)
     
    , Jan 5, 2014
    #8
  9. On 1/5/14 2:39 PM, wrote:
    > Il giorno venerdì 13 marzo 2009 08:52:39 UTC+1, koranthala ha scritto:
    >> Hi,
    >> Is it possible to convert a string to a function parameter?
    >> Ex:
    >> str = 'True, type=rect, sizes=[3, 4]'
    >> and I should be able to use it as:
    >> test(convert(str)) and the behaviour should be same as calling test
    >> with those values :
    >> i.e. test(True, type=rect, sizes=[3, 4])
    >>
    >> I tried eval, but it did not work. And any other mechanism I think
    >> turns out to be creating a full fledged python parser.
    >>
    >> Is there any mechanism with which we can do this straight away?

    >
    > I need the exact opposite, what is the inverse function?
    > example: i pass to a function an argument
    >
    > m=[654,54,65]
    > def function(m):
    > return takethenameof(m)
    >
    > and it have to return to me 'm' not [654,54,65] or '[654,54,65]'
    >
    > anybody can help?
    > i think that when one is talking about a function he have to talk also of the inverse function (also because google have problems searching about this...)
    >


    The difficulty in writing such a function is that values don't have
    unique names, if they have names at all. What should be returned in
    these cases?

    m = [654, 54, 65]
    def function(m):
    m2 = m
    m3 = m[:]
    takethenameof(m)
    takethenameof(m2)
    takethenameof(m3)
    takethenameof(m[:])
    takethenameof(2)
    takethenameof(2+2)

    There are samples online that try to do a "reasonable" job of this, but
    my googling isn't turning them up...

    --
    Ned Batchelder, http://nedbatchelder.com
     
    Ned Batchelder, Jan 5, 2014
    #9
  10. koranthala

    Gary Herron Guest

    On 01/05/2014 11:39 AM, wrote:
    > Il giorno venerdì 13 marzo 2009 08:52:39 UTC+1, koranthala ha scritto:
    >> Hi,
    >> Is it possible to convert a string to a function parameter?
    >> Ex:
    >> str = 'True, type=rect, sizes=[3, 4]'
    >> and I should be able to use it as:
    >> test(convert(str)) and the behaviour should be same as calling test
    >> with those values :
    >> i.e. test(True, type=rect, sizes=[3, 4])
    >>
    >> I tried eval, but it did not work. And any other mechanism I think
    >> turns out to be creating a full fledged python parser.
    >>
    >> Is there any mechanism with which we can do this straight away?

    > I need the exact opposite, what is the inverse function?
    > example: i pass to a function an argument
    >
    > m=[654,54,65]
    > def function(m):
    > return takethenameof(m)
    >
    > and it have to return to me 'm' not [654,54,65] or '[654,54,65]'
    >
    > anybody can help?
    > i think that when one is talking about a function he have to talk also of the inverse function (also because google have problems searching about this...


    Absolutely not. Objects (like [654,54,65]) do not have names, never did
    and never will! Objects do have a type and a value (and an identity),
    but not a name.

    Various namespaces will have dictionary-like associations between a name
    (like "m") and an object, and it *is* possible to get your hands on a
    (dictionary representing a) namespace and search it, but this is
    troublesome.

    For instance, consider this small variation of your code:

    def function(m):
    return takethenameof(m)

    a=[654,54,65]
    b = a
    function(a)

    While function is running, there will be three names associated with the list object.
    The outer namespace will have "a" and "b" associated with the list object,
    and the namespace local to function will have "m" associated with the same object.
    That's one object associated with three names in two different namespaces.

    Gary Herron
     
    Gary Herron, Jan 5, 2014
    #10
    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. Stefan Dammeier

    set vm-parameter when converting to jar?!

    Stefan Dammeier, Sep 1, 2005, in forum: Java
    Replies:
    2
    Views:
    427
    Roedy Green
    Sep 2, 2005
  2. nephish
    Replies:
    2
    Views:
    459
    John Machin
    Jul 5, 2007
  3. Replies:
    1
    Views:
    804
    Barry
    Jan 25, 2008
  4. Mister B
    Replies:
    8
    Views:
    569
    Nick Keighley
    Aug 26, 2010
  5. AzamSharp
    Replies:
    2
    Views:
    187
Loading...

Share This Page