473,400 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,400 software developers and data experts.

Hard to understand 'eval'

Hi,

It seems to be strange that give me syntax error inside an eval statement.
I'm looking at it carefully but I can't see any flaw.

Here it's part of the code:

for nn in stn_items:
value= eval('cp.%s' %nn)
if value and (nn in 'log, trash, multithread, verbose, download'):
cfl[wchkey][nn]= chkbool(value)
continue
if value:
cnfg= 'cfl[wchkey][nn]= _%s(value)' %nn
eval(cnfg)

And the output on pdb:

(Pdb) p cnfg
'cfl[wchkey][nn]=_append(value)'
(Pdb) p cfl[wchkey][nn]
False
(Pdb) eval('cfl[wchkey][nn]= _append(value)')
*** SyntaxError: invalid syntax (<string>, line 1)
(Pdb) p value
'230k'
(Pdb) p nn
'append'

Obviously I've an _append() function to convert into decimal the given value.

Other "eval" before this not issuing problems and also rather complicated,
but I'm not seeing the error here.
I'd like to study a class that might get a string and convert it into
function, once it's found inside the program.

--
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
Jun 27 '08 #1
10 1205
On 14 juin, 10:31, TheSaint <fc14301...@icqmail.comwrote:
Hi,

It seems to be strange that give me syntax error inside an eval statement.
I'm looking at it carefully but I can't see any flaw.

Here it's part of the code:

for nn in stn_items:
value= eval('cp.%s' %nn)
Hem... Not obvious from this snippet, but what's wrong with
getattr(cp, nn) ?

Jun 27 '08 #2
On 04:08, domenica 15 giugno 2008 br*****************@gmail.com wrote:
what's wrong with getattr(cp, nn) ?
The learning curve to get into these programming ways.
Does gettattr run the snippet passed in?
Considering that nn is a name of function, which will be called and (cfl,
value) are the parameters to passed to that function.

I'll spend some bit on getattr use.
--
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
Jun 27 '08 #3
On 06:34, domenica 15 giugno 2008 Dennis Lee Bieber wrote:
> for nn in stn_items:
I already see a syntax error when viewing that in Agent... A missing
indent level under the "for"
The program don't complain wrong indentation, I mostly sure a wrong
copy-paste error.
Error doesn't come up there.
. You also don't need the continue if you change the second if into elif.
My mistake, I thought that was improving the loop.

is it an if....elif....elif probing only the first matching case and drop the
remaining checks?
And what type of structure is "cfl"?
You got close, that's a dictionary of dictionaries and I'm trying to updating
it.
wonder what this mysterious _append() function is supposed to be doing;
Append() is a conventional name regarding a file logging.
There would be an option to set a quota of bytes size.
Huh... I presume you mean to convert from a text decimal
it isn't so, the function look at the string to see if ending by K or M,
which means Kbytes or Mbytes. It'll return the decimal conversion.
If the value is set as boolean value, then it will do appending to the log
when it True or stop appending when there's a quota.

def _append(c, v):
RE_BYTE= re.compile(r'^[\d]+(k|m)?$',re.I)
# any number of digit followed by 0 or 1 (k or m), case insensitive
chkbool(v)
if isinstance(v,bool):
c['append']= v
return c
if RE_BYTE.match(value):
k= 1024; M= k * k; v= int(value[:-1])
if value[-1:] == 'k': v= v * k
if value[-1:] == 'm': v= v * m
c['append']= v
return c

All the code could be download at my web site ;)
But this here it's a bit new concept.
--
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
Jun 27 '08 #4
The point here is that eval() use is general frowned upon. If you
don't understand it or the alternatives, then you probably don't
understand it well enough to make the call on using it or not.

If you need just look up an attribute where the name of the attribute
is in a variable, use getattr(obj, attribute_name). If you need to
call a method somewhere, you should have both the name of the method
and the list of arguments to call it with, such as getattr(obj,
methname)(a, b, c). Does this make sense?

On Jun 15, 2008, at 5:16 AM, TheSaint wrote:
On 04:08, domenica 15 giugno 2008 br*****************@gmail.com wrote:
>what's wrong with getattr(cp, nn) ?

The learning curve to get into these programming ways.
Does gettattr run the snippet passed in?
Considering that nn is a name of function, which will be called and
(cfl,
value) are the parameters to passed to that function.

I'll spend some bit on getattr use.
--
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list
Jun 27 '08 #5
On Jun 16, 7:05 am, Dennis Lee Bieber <wlfr...@ix.netcom.comwrote:
On Sun, 15 Jun 2008 17:45:12 +0800, TheSaint <fc14301...@icqmail.com>
declaimed the following in comp.lang.python:
is it an if....elif....elif probing only the first matching case and drop the
remaining checks?

Unless the compile/interpret pass is very unoptimized, once a branch
has been taken, the others should be totally skipped.
Don't you mean "Unless the "compile/interpret pass is VERY VERY
BROKEN", as in "omits to drop in a jump to the end of the 'if'
statement after each chunk of action code"?
Jun 27 '08 #6
On 01:15, lunedì 16 giugno 2008 Calvin Spealman wrote:
such as getattr(obj,
methname)(a, b, c). Does this make sense?
This is big enlightenment :) Thank you! :)

I found problem with eval() when it comes to pass quoted strings.
I circumvent that by encapsulating the strings in variable or tuple.
The principle is to have a name which will refers a function somewhere in the
program and to call that function, plus additional data passed in.

In other word I'd expect something:

function_list= ['add' ,'paint', 'read']
for func in function_list:
func(*data)
I tried getattr, and I saw that result. I only investigate a little, soI
still have a small perplexity.

--
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
Jun 27 '08 #7
On 05:05, 16-6- 2008 Dennis Lee Bieber wrote:
> # any number of digit followed by 0 or 1 (k or m), case insensitive

I don't do regular expressions... and the comment doesn't help
"digit followed by 0 or 1", when 0/1 ARE digits themselves...
That means either none or one letter, of which k or m are allowed.
c is a mutable object; you don't have to return it; the change is
seen by anything holding a reference to the object.
C is a dictionary, it might be omitted, but I'm still not sure if will lose
its state.
Again, as c is mutable, it doesn't need to be returned.
Apparently
Not so apparent, it's doing that, buddy :)
v = v.strip().lower()
regexp did a fine check and case insensitive, but I like your idea too.
Biggest flaw, in my mind... You are using ONE identifier to control
TWO meanings... a boolean On/Off control AND an integer size limit
control.
That occupy only small variable and as long as python can accept anything not
zero, false or none for an _if_ condition, that might be allowable, I think.
Then if not zero will mean the log will be *appended* to an existing file and
if the value is something that can be converted in decimal value, then this
will set the quota for the log file, as well.
Here below dbg is the log file and if it isn't None then s a valid file path
should work.

dbg= sttng['log']; mode= 'w' # normally write, it writes new
try:
if sttng['append'] Path.getsize(dbg): mode= 'a'
except (OSError, TypeError): # found a boolean or dbg is new file
pass

So 5 line of code can do me the job smartly, I think ;)

--
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
Jun 27 '08 #8
En Sat, 14 Jun 2008 05:31:35 -0300, TheSaint <fc********@icqmail.comescribió:
It seems to be strange that give me syntax error inside an eval statement.
I'm looking at it carefully but I can't see any flaw.

Here it's part of the code:

for nn in stn_items:
value= eval('cp.%s' %nn)
if value and (nn in 'log, trash, multithread, verbose, download'):
cfl[wchkey][nn]= chkbool(value)
continue
if value:
cnfg= 'cfl[wchkey][nn]= _%s(value)' %nn
eval(cnfg)

And the output on pdb:

(Pdb) p cnfg
'cfl[wchkey][nn]=_append(value)'
(Pdb) p cfl[wchkey][nn]
False
(Pdb) eval('cfl[wchkey][nn]= _append(value)')
*** SyntaxError: invalid syntax (<string>, line 1)
Others have already remarked that your general approach is bad ("don't use eval!", in short). But none has pointed out the actual error in your code: eval can accept only an *expression*, not a statement. eval("x=1") gives the same SyntaxError.
(`exec` is the way to execute statements, but the same caveats apply, so: don't use exec either, use getattr/setattr instead)

--
Gabriel Genellina

Jun 27 '08 #9
TheSaint a écrit :
On 04:08, domenica 15 giugno 2008 br*****************@gmail.com wrote:
>what's wrong with getattr(cp, nn) ?

The learning curve to get into these programming ways.
Does gettattr run the snippet passed in?
Nope, it just does what the name implies.
Considering that nn is a name of function, which will be called and (cfl,
value) are the parameters to passed to that function.
Everything in Python's an object (at least anything you can bind to a
name), including functions and methods. Once you have a callable object,
you just have to apply the call operator (parens) to call it. In your
case, that would be:

func = getattr(cc, nn, None)
if callable(func):
result = func(cfl, value)
else:
do_whatever_appropriate_here()
I'll spend some bit on getattr use.
Would be wise IMHO.
Jun 27 '08 #10
TheSaint a écrit :
On 01:15, lunedì 16 giugno 2008 Calvin Spealman wrote:
>such as getattr(obj,
methname)(a, b, c). Does this make sense?

This is big enlightenment :) Thank you! :)

I found problem with eval() when it comes to pass quoted strings.
I circumvent that by encapsulating the strings in variable or tuple.
The principle is to have a name which will refers a function somewhere in the
program and to call that function, plus additional data passed in.

In other word I'd expect something:

function_list= ['add' ,'paint', 'read']
for func in function_list:
func(*data)
Can't work - function_list is a list of strings, not a list of
functions. If the functions you intend to call are already bound to
names in the current scope, you don't even need any extra lookup
indirection:

def add(*args):
# code here

from some_module import paint

obj = SomeClass()
read = obj.read

functions = [add, paint, read]
args = [1, 2]
for func in functions:
func(*args)

I tried getattr,
getattr is useful when you only have the name of the
function/method/whatever attribute as a string. And a target object
(hint: modules are objects too) of course - if the name lives either in
the global or local namespace, you can access it by name using the dicts
returned by resp. the globals() and locals() functions.

HTH
Jun 27 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Wayne Wengert | last post by:
I am using a Gridview in an ASP.NET 2.0 (VB) application. In a hyperlink template column I want to build a url wich includes passing a couple of query strings that I need to populate dynamically. ...
15
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
3
by: ray_usenet | last post by:
Why is this: eval('') is OK, but eval('{"active":"true"}') tells me I'm missing ";" ? Then why is it that if I put parentheses around the second statement:
2
by: Bruno Rafael Moreira de Barros | last post by:
index.php --- inlcude 'application.php'; functions.php --- function test1() { trigger_error('My error'); return FALSE;
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.