473,322 Members | 1,403 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,322 software developers and data experts.

eval function not working how i want it dag namn

hi everybody
I've written this function to make a list of all of an objects
attributes and methods (not for any reason, I'm just learning)

def list_members(obj)
l = dir(obj)
return map(lambda x : eval('obj.'+x), l)

but I get an error saying that obj isn't defined. As I understand it
eval has access to the current local namespace, which does contain
object, so I'm not sure whats going wrong.

ps Im sure there are better ways of doing the above which doesn't call
the eval function, and while I'd be glad to know what it is, I'd still
like to understand why my way isnt working

thanks

Jul 19 '05 #1
7 1879
robcarlton wrote:
I've written this function to make a list of all of an objects
attributes and methods (not for any reason, I'm just learning)

def list_members(obj)
l = dir(obj)
return map(lambda x : eval('obj.'+x), l)


That works fine for me with Python 2.4.

This is the best way to do it:

def list_members(obj):
return [getattr(obj, name) for name in dir(obj)]

Although personally I would prefer to have this information in dict
form, so i'd use:

return dict((name, getattr(obj, name)) for name in dir(obj))

For objects defined in CPython, you can use obj.__dict__, but this is
somewhat hacky, and I'd avoid it.
--
Michael Hoffman
Jul 19 '05 #2
How about using the vars builtin?

Michael Hoffman schrieb:
robcarlton wrote:
I've written this function to make a list of all of an objects
attributes and methods (not for any reason, I'm just learning)

def list_members(obj)
l = dir(obj)
return map(lambda x : eval('obj.'+x), l)

That works fine for me with Python 2.4.

This is the best way to do it:

def list_members(obj):
return [getattr(obj, name) for name in dir(obj)]

Although personally I would prefer to have this information in dict
form, so i'd use:

return dict((name, getattr(obj, name)) for name in dir(obj))

For objects defined in CPython, you can use obj.__dict__, but this is
somewhat hacky, and I'd avoid it.


--
GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634

Jul 19 '05 #3
robcarlton wrote:
hi everybody
I've written this function to make a list of all of an objects
attributes and methods (not for any reason, I'm just learning)

def list_members(obj)
l = dir(obj)
return map(lambda x : eval('obj.'+x), l)

but I get an error saying that obj isn't defined. As I understand it
eval has access to the current local namespace, which does contain
object, so I'm not sure whats going wrong.

ps Im sure there are better ways of doing the above which doesn't call
the eval function, and while I'd be glad to know what it is, I'd still
like to understand why my way isnt working


It would work if obj were in the local namespace like so:
def f(obj="x"): .... return eval("obj")
.... f() 'x'

but with the lambda you are introducing a nested namespace.
def f(obj="x"): .... return (lambda: eval("obj"))()
.... f() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f
File "<stdin>", line 2, in <lambda>
File "<string>", line 0, in ?
NameError: name 'obj' is not defined

You are doing the equivalent to
def f(obj="x"): .... def g(): # no obj in g()'s namespace
.... return eval("obj")
.... return g()
.... f() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in f
File "<stdin>", line 3, in g
File "<string>", line 0, in ?
NameError: name 'obj' is not defined

only in a convoluted way. Let's make f()'s local variable obj visible in
g(), too:
def f(obj="x"): .... def g():
.... obj # now you can see me
.... return eval("obj")
.... return g()
.... f() 'x'

Here's another way that is viable with lambda, too.
def f(obj="x"): .... return (lambda obj=obj: eval("obj"))()
.... f() 'x'

I'm sure you can fix your list_members() accordingly. Note that rebinding
obj between the definition and call of g() will affect the result only in
the first of the last two examples.

And now for something completely different:
def list_members(obj): .... return [getattr(obj, name) for name in dir(obj)]
.... import os
list_members(os)[:5] [73, 78, 65, 74, 68]


Peter

Jul 19 '05 #4
Michael Hoffman wrote:
def list_members(obj)
l*=*dir(obj)
return*map(lambda*x*:*eval('obj.'+x),*l)


That works fine for me with Python 2.4.


Python 2.4 (#6, Jan 30 2005, 11:14:08)
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
def lm(obj): .... l = dir(obj)
.... return map(lambda x: eval("obj." + x), l)
.... class X: .... pass
.... x = X()
x.question = "Are you sure?"
lm(x) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in lm
File "<stdin>", line 3, in <lambda>
File "<string>", line 0, in ?
NameError: name 'obj' is not defined


Peter

Jul 19 '05 #5
Peter Otten wrote:
Michael Hoffman wrote:
def list_members(obj)
l = dir(obj)
return map(lambda x : eval('obj.'+x), l)


That works fine for me with Python 2.4.

x.question = "Are you sure?"


I should clarify. It works fine for me when I've already globally
assigned obj to something else. D'oh!
--
Michael Hoffman
Jul 19 '05 #6
thanks. I'll use the getattr function now, and I think I understand
where I went wrong with eval. I was thinking in Lisp where the lexical
scope would mean that obj is defined

Jul 19 '05 #7
robcarlton wrote:
thanks. I'll use the getattr function now, and I think I understand
where I went wrong with eval. I was thinking in Lisp where the lexical
scope would mean that obj is defined


The full story is actually more subtle. The name 'obj'
*is* accessible from a nested scope if you do something
like

def f(obj):
def g():
print obj
g()

But the bytecode compiler has to do extra work to make
a name in an intermediate scope accessible to an inner
scope, and it only does this if it sees a reference to
the name in the inner scope. In your code, the reference
is invisible at compile time, so the compiler misses it,
and the run-time evaluation fails.

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #8

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

Similar topics

6
by: Bill | last post by:
Hi I have a form called 'store' with many fields, and I can update the 'name' field ok like this document.store.name.value = n; //this works fine but I want a function to update any field,...
12
by: knocte | last post by:
Hello. I have always thought that the eval() function was very flexible and useful. If I use it, I can define functions at runtime!! However, I have found a case where eval() does not work...
18
by: Joe Fallon | last post by:
I have some complex logic which is fairly simply to build up into a string. I needed a way to Eval this string and return a Boolean result. This code works fine to achieve that goal. My...
1
by: Joel Byrd | last post by:
I've been using an eval() statement, which has been working fine until I put it inside of a function. Is this a known problem, and is there a known solution/work-around to this?
7
by: | last post by:
I have what's probably a simple page lifecycle question related to dynamically evaluating values that are placed by a repeater and dynmically placing user controls that use those values. I'm...
4
by: Jon Slaughter | last post by:
I'm using eval to excute some mixed php and html code but I cannot debug it. I am essentially using filegetcontents to load up a php/html file and then inserting it into another php/html file and...
6
by: vasudevram | last post by:
Hi group, Question: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? I wrote a function to generate other functions using something like eval("def foo: ....") but...
6
by: RandomElle | last post by:
Hi there I'm hoping someone can help me out with the use of the Eval function. I am using Access2003 under WinXP Pro. I can successfully use the Eval function and get it to call any function with...
10
by: Gordon | last post by:
I have a script that creates new objects based on the value of a form field. Basically, the code looks like this. eval ('new ' + objType.value + '(val1, val2, val3'); objType is a select with...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.