Go Back   Rhinocerus > Newsgroup > Newsgroup comp.lang.python

Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old 03-13-2009, 06:52 AM
koranthala
Guest
 
Posts: n/a
Default converting a string to a function parameter

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?



Reply With Quote
Alt Today
Advertising
 
and become member of Rhinocerus
Standard Sponsored Links

  #2 (permalink)  
Old 03-13-2009, 07:01 AM
Chris Rebert
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

On Fri, Mar 13, 2009 at 12:52 AM, koranthala <koranthala@gmail.com> 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
Reply With Quote
  #3 (permalink)  
Old 03-13-2009, 07:15 AM
koranthala
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

On Mar 13, 1:01*pm, Chris Rebert <c...@rebertia.com> wrote:
> On Fri, Mar 13, 2009 at 12:52 AM, koranthala <koranth...@gmail.com> 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.


Reply With Quote
  #4 (permalink)  
Old 03-13-2009, 12:19 PM
odeits
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

On Mar 13, 12:52*am, koranthala <koranth...@gmail.com> 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
Reply With Quote
  #5 (permalink)  
Old 03-13-2009, 03:20 PM
Scott David Daniels
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

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.


This might work [again be avoid eval if possible].
You _might want to do something like:

def _args(*_nargs, **_kwargs):
'''Collect call parameters from a call'''
return _nargs, _kwargs
...
nargs, kwargs = eval('_args(%s)' % arglist
...
test(*nargs, **kwargs)

--Scott David Daniels
Scott.Daniels@Acm.Org
Reply With Quote
  #6 (permalink)  
Old 03-13-2009, 03:46 PM
Aaron Brady
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

On Mar 13, 2:52*am, koranthala <koranth...@gmail.com> 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.
Reply With Quote
  #7 (permalink)  
Old 03-13-2009, 07:21 PM
Paul McGuire
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

On Mar 13, 11:46*am, Aaron Brady <castiro...@gmail.com> wrote:
> On Mar 13, 2:52*am, koranthala <koranth...@gmail.com> 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]}

Reply With Quote
  #8 (permalink)  
Old 03-13-2009, 08:45 PM
Aaron Brady
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

On Mar 13, 3:21*pm, Paul McGuire <pt...@austin.rr.com> wrote:
> On Mar 13, 11:46*am, Aaron Brady <castiro...@gmail.com> wrote:
>
>
>
> > On Mar 13, 2:52*am, koranthala <koranth...@gmail.com> 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(...)
?
Reply With Quote
  #9 (permalink)  
Old 03-28-2009, 10:37 AM
andrew cooke
Guest
 
Posts: n/a
Default Re: converting a string to a function parameter

I'm a bit late to the party, but LEPL 2.2, just released, can now handle
this too. I suspect email may mangle this, so you can also read it at
http://www.acooke.org/lepl/examples....-argument-list


from lepl import *

comma = Drop(',')
none = Literal('None') >> (lambda x: None)
bool = (Literal('True') | Literal('False')) >> (lambda x: x == 'True')
ident = Word(Letter() | '_',
Letter() | '_' | Digit())
float_ = Float() >> float
int_ = Integer() >> int
str_ = String() | String("'")
item = str_ | int_ | float_ | none | bool | ident

with Separator(~Regexp(r'\s*')):
value = Delayed()
list_ = Drop('[') & value[:, comma] & Drop(']') > list
tuple_ = Drop('(') & value[:, comma] & Drop(')') > tuple
value += list_ | tuple_ | item
arg = value >> 'arg'
karg = (ident & Drop('=') & value > tuple) >> 'karg'
expr = (karg | arg)[:, comma] & Drop(Eos()) > Node

parser = expr.string_parser()

ast = parser('True, type=rect, sizes=[3, 4], coords = ([1,2],[3,4])')
print(ast[0])


which gives:

Node
+- arg True
+- karg (u'type', u'rect')
+- karg (u'sizes', [3, 4])
`- karg (u'coords', ([1, 2], [3, 4]))

you can then access those values:
>>> ast[0].arg

[True]
>>> ast[0].karg

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

alternatively, you could avoid using a Node altogether and just put them
in a list or whatever....

andrew



Paul McGuire wrote:
> 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]}
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



Reply With Quote
 
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: md5() function - where to find documentation ? Paul Dorfman Newsgroup comp.soft-sys.sas 0 10-30-2007 05:37 PM
proc report need number to be date gscsrc@hotmail.com Newsgroup comp.soft-sys.sas 11 10-29-2007 03:46 PM
Re: Function reference with versions ? Choate, Paul@DDS Newsgroup comp.soft-sys.sas 0 03-20-2006 04:59 PM
Re: How to build Dynamic Variable names and values Arthur Tabachneck Newsgroup comp.soft-sys.sas 0 02-11-2006 06:34 PM
Re: preserve case using CALL PRXCHANGE Guido T Newsgroup comp.soft-sys.sas 0 07-29-2005 10:42 AM



All times are GMT. The time now is 12:45 AM.


Copyright ©2009

LinkBacks Enabled by vBSEO 3.3.0 RC2 © 2009, Crawlability, Inc.