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(ob j)
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 7 1912
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(ob j) 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(ob j):
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
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(ob j) 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(ob j): 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
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(ob j) 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(ob j):
.... return [getattr(obj, name) for name in dir(obj)]
.... import os list_members(os )[:5]
[73, 78, 65, 74, 68]
Peter
Michael Hoffman wrote: def list_members(ob j) l*=*dir(obj ) return*map(la mbda*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
Peter Otten wrote: Michael Hoffman wrote:
def list_members(ob j) l = dir(obj) return map(lambda x : eval('obj.'+x), l)
That works fine for me with Python 2.4.
x.questio n = "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
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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, so would like to do something
like this:
|
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 properly. It
works, for example, when invoking functions (alert('hello')), but not
for defining functions.
The case occurs when retrieving the javascript code with
|
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 question is what happens to the dynamically created assembly when the
method is done running? Does GC take care of it?
Or is it stuck in RAM until the ASP.Net process is recycled?
This code executes pretty frequently (maybe 4 times per transaction) and...
|
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?
|
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 attempting to bind a user control I've written, "ImageBox", to a
repeater.
The user control takes a custom property, "ContentID", that will execute a
database lookup and load an image.
| |
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 then using eval to execute the
final product.
If I were to use include and output buffering instead of filegetcontents
would it allow be to debug the code? (I have to capture the include so it
can be modified which is why I used...
|
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 it gave a syntax error ("Invalid syntax") with caret pointing to
the 'd' of the def keyword.
|
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 or without parms. I know that any function that is passed to Eval() must be declared Public. It can be a Sub or Function, as long as it's Public. I even have it where the "function" evaluated by Eval can be in a form (class) module or in a standard...
|
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 the different types of objects you can create
as values.
I really don't like using eval, and it's causing problems, like if I
do something like the following:
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |