473,796 Members | 2,904 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using eval, or something like it...

r0g
Hi There,

I know you can use eval to dynamically generate the name of a function
you may want to call. Can it (or some equivalent method) also be used to
do the same thing for the variables of a class e.g.

class Foo():
bar = 1
gum = 2

mylist = ['bar','gum']

a = Foo()
for each in mylist:
a.eval(each) = 999
If so, what is the proper syntax/method for this.

Regards,

Roger.
Nov 20 '08
15 1794
On Nov 20, 6:54*pm, r0g <aioe....@techn icalbloke.comwr ote:
It would seem from this setattr function that the proper term for these
is 'attributes'. That for many years I have considered pretty much any
named thing that may vary a 'variable' might be at the root of the
problem here as it's a very un-specific term...
Exactly, refrain from using the term "variable", or "value" for that
matter, in Python context as they are notorious for causing more
trouble than they deserve..
So I gather you are saying that the fragments of state within a class
are so distinct from ordinary common or garden variables that it is
incorrect to think of them, or describe them, as variables, much like
quarks should not really be regarded as distinct particles, and they
should only be thought of and described as 'attributes' to avoid confusion?

Is this correct enough for me to avoid the aforementioned bug pile?
No, a class can have attributes just like a instance can, and you can
use setattr() to set an attribute for a class just like you do it for
instances:

class Foo():
bar = 1
gum = 2
>>setattr(Foo , 'bar', 3)
Foo.bar
3

George
Nov 21 '08 #11
On Thu, 20 Nov 2008 11:12:56 +1000, James Mills wrote:
DON'T USE eval!
If you're going to make a sweeping generalization like that, at least
offer some alternatives, and explain why eval should be avoided.
Otherwise your advice is just cargo-cult programming.

eval is not inherently bad, it does have its uses. The timeit module, for
instance, uses eval. But in general, there are better, faster ways of
doing things than eval.

In my own testing, I find that eval('code') causes a serious speed hit:
it's about ten times slower than just executing code directly.

eval also is a security risk, if you can't trust the code you are passing
to it. You can *try* to mitigate those risks by filtering the string, and
by setting the globals and locals arguments to eval, but you can't
entirely remove the risk. The best way to remove the risk is to never use
eval on untrusted code.

--
Steven
Nov 21 '08 #12
r0g
Scott David Daniels wrote:
r0g wrote:
>...
A class is like a template which combines a complex data type (made from
a combination of other data types) and the methods that operate on that
data type.

You generally don't work with classes directly but you make instances of
them, each instance has it's own internal state and methods, initially
these are the same as the templates but can be changed or overridden
without affecting the state of any other instances you might have.
Take the tutorial and do experiments.
The attribute lookup checks the class _and_ the instance (with the
instance over-riding the class). Make sure you can explain the output
from this:

class Demo(object):
non_template = 43

d = Demo()
print d.non_template
Demo.non_templa te = 44
print d.non_template
d.non_template = 45
print d.non_template
Demo.non_templa te = 46
print d.non_template

Once you can do that, explain this:
class Demo2(object):
holder = []

e = Demo2()
print e.holder
Demo2.holder.ap pend(44)
print e.holder
e.holder.append (45)
print e.holder
Demo2.holder.ap pend(46)
print e.holder

# clue:
print d.holder is Demo.holder

Well that all makes sense what with Pythons' 'only copy explicity' and
lists being mutable and indeed, as you intuited, I did run into issues
with this within days of starting to learn Python! Ever since I have
been using copy.deepcopy() when I need to get the results described
above i.e. to ensure each instance is fully independent of all the others.

I hadn't really appreciated the consequences of this till now though
e.g. that an instance might do a = a + 1 without affecting it's siblings
but that b.append("fish" ) would affect b for everyone. I don't know if I
will find any uses for that kind of behaviour but it doesn't hurt to
understand it :-)

Isn't Python's behaviour a little peculiar in this respect though,
compared to classes in other languages? i.e. Are instances in other OO
languages like Smalltalk, C++ fully independent copies or do their
attribute names just point to one common object until reassigned like in
python? (Or have I still not it at all?!)

>Is this correct enough for me to avoid the aforementioned bug pile?

Also then, what _is_ an "instance variable" ?

Well, when you use the term variable, I suspect that you think it
represents storage. OK, it kind of does, but only in the sense
Well you used the term "instance variable" in your reply so I was just
asking if there _is_ an actual thing known as "an instance variable" in
Python and if so what it is/does.

Thanks for your reply and examples BTW (I think) they are helping me
clarify my understanding of python classes and the language used to
describe them.
Roger.
--Scott David Daniels
Sc***********@A cm.Org
Nov 21 '08 #13
On Nov 21, 2008, at 8:58 AM, r0g wrote:
I hadn't really appreciated the consequences of this till now though
e.g. that an instance might do a = a + 1 without affecting it's
siblings
but that b.append("fish" ) would affect b for everyone. I don't know
if I
will find any uses for that kind of behaviour but it doesn't hurt to
understand it :-)
Yes, it's critical to understanding any OOP language.
Isn't Python's behaviour a little peculiar in this respect though,
compared to classes in other languages?
No, it's exactly the same.
i.e. Are instances in other OO
languages like Smalltalk, C++ fully independent copies or do their
attribute names just point to one common object until reassigned
like in
python? (Or have I still not it at all?!)
You're still a little confused, perhaps. But I think this will clear
it up:

<http://www.strout.net/info/coding/valref/>

I wrote this to help people in exactly your situation, so please do
give me feedback and let me know how it did or didn't help.

Thanks,
- Joe

Nov 21 '08 #14
I forgot to include a few cases:

(1) Inspired by your calling the class attributes "templates" :
class Demo3(object):
pass

d = Demo3()
print d.non_template # raises exception
d.non_template = 45
print d.non_template
print Demo3.non_templ ate # raises exception
Demo3.non_templ ate = 44
print d.non_template
print Demo3.non_templ ate # raises exception
del d.non_template
print d.non_template
del d.non_template # raises exception
print d.non_template
del Demo3.non_templ ate
print d.non_template # raises exception

All the above to demonstrate the class storage and instance storage
are separate.

(2) Trickier stuff involving sharing:
class Demo4(object):
common = []

g = Demo4()
h = Demo4()
g.common.append ('a')
print g.common, h.common, Demo4.common
g.common = g.common
Demo4.common = Demo4.common + ['b']
h.common = h.common
x = Demo4()
g.common.append ('c')
h.common.append ('d')
x.common.append ('e')
print g.common, h.common, Demo4.common, x.common
Thanks for your reply and examples BTW (I think) they are helping me
clarify my understanding of python classes and the language used to
describe them.
They are meant to point out that you need to read language definitions
carefully, or you will breeze by thinking you understand something you
really do not understand. Python provides a great way to experiment
with things you think you get; try "corner cases" to make sure you
know what is going on.

--Scott David Daniels
Sc***********@A cm.Org
Nov 21 '08 #15
r0g
Scott David Daniels wrote:
I forgot to include a few cases:

(1) Inspired by your calling the class attributes "templates" :

I did no such thing, I likened classes to templates and as far as I can
tell they are _like_ templates albeit dynamic ones.

class Demo3(object):
All the above to demonstrate the class storage and instance storage
are separate.
I see that.
(2) Trickier stuff involving sharing:
class Demo4(object):
Yeah no s*** that's trickier! Still haven't quite wrapped my head round
it yet even after reading the 'language definitions carefully' (well
http://www.python.org/doc/2.5.2/tut/node11.html at least) although I am
a bit clearer about the difference between class attributes and instance
variables. Time to go rewrite some crappy old code!
They are meant to point out that you need to read language definitions
carefully, or you will breeze by thinking you understand something you
really do not understand.
One of the things I love about Python is how it allows you to just
breeze by on intuition alone! It makes it immediately (and
incrementally) useful in the real world and I've been ableto built up a
great little library of scripts as I've learned. Having said that I
appreciate bigger projects require a deeper understanding which is why I
hang out here and occasionally ask dumb questions. Thankfully from time
to time clever bods like you will spot and point out the gaps in my
knowledge.

Cheers,

Roger.
Nov 21 '08 #16

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

Similar topics

21
8544
by: hemant.singh | last post by:
Hello all, I am try'g to send window.location.href to the server script who will generate dynamic javascript according to the referral name comg in as param Now bcz <script language="javascript" src="NO JAVASCRIPT CAN BE USED HERE" /> So I am see'g If I can use eval todo something what I am doing I have tried almost everything, following is being last one
1
2129
by: Bob Tinsman | last post by:
I've been interested in E4X because my company has an XML schema that we usually manipulate through a Java mapping generated by Castor, which I think is fairly tedious, and which means you have to do everything in the webapp. I think it'd be cool to suck in the XML, tweak it in the browser, then use a SOAP call to submit it to the server. Anyhow, we use namespaces on all our elements, and I was trying to avoid using the "ns::elementname"...
2
10342
by: Arvan | last post by:
hi,all. i wanna use Eval("DataField") to bind datarow in item template of GridView. for example: <asp:Label runat="server" id="Label1" text='<%# Eval("DataField") %>'><asp:Label> but how to use eval with control HyperLink?
2
2460
by: MrCrool | last post by:
Hi I need to be able to handle the following ASP programming in pure C# code: <asp:TemplateColumn HeaderText="Customer Information"> <ItemTemplate> <table border="0"> <tr> <td align="right"><b>Name:</b></td> <td><%# DataBinder.Eval(Container.DataItem, "name") %></td>
7
5065
by: Darko | last post by:
Hello, I have this particular problem with eval() when using Microsoft Internet Explorer, when trying to define an event handler. This is the code: function BigObject() { this.items = new Array(); this.values = new Array();
7
402
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I access a property of an object using a string? ----------------------------------------------------------------------- There are two ways to access properties: the dot notation and the square bracket notation. What you are looking for is the square bracket notation in which the dot, and the identifier to its right, are replaced with a set of...
3
1517
by: Michal Lipinski | last post by:
Hi its my first post. I have a problem, I want to user eval() function in a for loop to set labels to staticText so i done something like this: dzien=self.components.Calendar.GetDate().GetDay() for i in range(1,8): act=dzien+i -1 eval( 'self.components.d' + str(i) + '.text = "'+ str(act) + '"')
13
3179
by: My Pet Programmer | last post by:
The way I usually set up and work with the XMLHttpRequest to execute server side functions and get results is this: var url = "someurl?params=" + params; var conn = createRequest(); // gets an XMLHttpRequest object conn.open("GET", url); conn.onreadystatechange = function () { if (conn.readyState == 4 && conn.status == 200) {
6
3557
Frinavale
by: Frinavale | last post by:
Apparently I have a lot of questions today regarding JavaScript security. I've implemented a JavaScript Object that intercepts page submits (postbacks) and then displays a UI prompting the user to confirm(yes)/deny(no)/cancel(close UI/cancel submit) their action. There may be additional JavaScript methods to execute before displaying the UI and may be additional JavaScript methods to execute upon closing the UI. I'm thinking about...
0
9535
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,...
0
10467
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10201
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10021
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 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...
0
9061
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7558
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 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...
1
4130
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
2
3744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2931
bsmnconsultancy
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...

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.