473,785 Members | 2,335 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 #1
15 1791
DON'T USE eval!

On Thu, Nov 20, 2008 at 10:44 AM, r0g <ai******@techn icalbloke.comwr ote:
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.
--
http://mail.python.org/mailman/listinfo/python-list


--
--
-- "Problems are solved by method"
Nov 20 '08 #2
On Nov 19, 7:44*pm, r0g <aioe....@techn icalbloke.comwr ote:
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.
for each in mylist:
setattr(a, each, 999)
HTH,
George
Nov 20 '08 #3
On Nov 20, 11:44*am, r0g <aioe....@techn icalbloke.comwr ote:
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.
You mention "variables of a class" but you then proceed to poke at an
instance of the class. They are two different things. Which do you
mean?

In any case, use the built-in function setattr to set attribute values
for an object or for a class.

setattr(a, 'bar', 999) is equivalent to a.bar = 999
setattr(Foo, 'bar', 456) is equivalent to Foo.bar = 456

Check out setattr (and getattr) in the docs.
Nov 20 '08 #4
r0g
George Sakkis wrote:
On Nov 19, 7:44 pm, r0g <aioe....@techn icalbloke.comwr ote:
>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.

for each in mylist:
setattr(a, each, 999)
HTH,
George
Thank you George!

Damn I love Python! :0D
Nov 20 '08 #5
r0g
John Machin wrote:
On Nov 20, 11:44 am, r0g <aioe....@techn icalbloke.comwr ote:
>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.

You mention "variables of a class" but you then proceed to poke at an
instance of the class. They are two different things. Which do you
mean?

In any case, use the built-in function setattr to set attribute values
for an object or for a class.

setattr(a, 'bar', 999) is equivalent to a.bar = 999
setattr(Foo, 'bar', 456) is equivalent to Foo.bar = 456

Check out setattr (and getattr) in the docs.

The former i.e. the variables of an instance of a class. Thanks :-)

Roger.
Nov 20 '08 #6
r0g wrote:
John Machin wrote:
>.... You mention "variables of a class" but you then proceed to poke
at an instance of the class....
Check out setattr (and getattr) in the docs.
The former i.e. the variables of an instance of a class. Thanks :-)
Careful here. Your wording seems to indicate you misunderstand the
Python model. The instance doesn't have variables (and your class built
nothing that could be called an instance variable). Think of the
attributes of an instance (or a class) as "values attached to (or
associated with) the instance." If you don't you are setting yourself
up to discover a pile of bugs that you don't understand.

--Scott David Daniels
Sc***********@A cm.Org
Nov 20 '08 #7
r0g
Scott David Daniels wrote:
r0g wrote:
>John Machin wrote:
>>.... You mention "variables of a class" but you then proceed to poke
at an instance of the class....
Check out setattr (and getattr) in the docs.
The former i.e. the variables of an instance of a class. Thanks :-)

Careful here. Your wording seems to indicate you misunderstand the
Python model. The instance doesn't have variables (and your class built
nothing that could be called an instance variable). Think of the
attributes of an instance (or a class) as "values attached to (or
associated with) the instance." If you don't you are setting yourself
up to discover a pile of bugs that you don't understand.

--Scott David Daniels
Sc***********@A cm.Org

OK now I'm confused, let me explain how I see things at the moment and
you can correct me...

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.

While the perceived wisdom is that you should encapsulate all the
methods you need to modify your classes' state within the class itself
Python does (for better or worse) permit you to reach inside a class and
futz with it's state directly from outside.

The bits of an instance's state one might futz with (from within or
without) i.e. the primitives that make up the complex object the class
is a representation of, I think of as it's variables.

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...

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?

Also then, what _is_ an "instance variable" ?

Thanks,
Roger.

Q: How many pedants does it take to change a lightbulb?
A: Well actually you mean "replace" a lightbulb.
Q: Have you ever kissed a girl?
Nov 20 '08 #8
On Thu, Nov 20, 2008 at 3:54 PM, r0g <ai******@techn icalbloke.comwr ote:
Scott David Daniels wrote:
>r0g wrote:
>>John Machin wrote:
.... You mention "variables of a class" but you then proceed to poke
at an instance of the class....
Check out setattr (and getattr) in the docs.
The former i.e. the variables of an instance of a class. Thanks :-)

Careful here. Your wording seems to indicate you misunderstand the
Python model. The instance doesn't have variables (and your class built
nothing that could be called an instance variable). Think of the
attributes of an instance (or a class) as "values attached to (or
associated with) the instance." If you don't you are setting yourself
up to discover a pile of bugs that you don't understand.

--Scott David Daniels
Sc***********@A cm.Org


OK now I'm confused, let me explain how I see things at the moment and
you can correct me...

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.

While the perceived wisdom is that you should encapsulate all the
methods you need to modify your classes' state within the class itself
Python does (for better or worse) permit you to reach inside a class and
futz with it's state directly from outside.

The bits of an instance's state one might futz with (from within or
without) i.e. the primitives that make up the complex object the class
is a representation of, I think of as it's variables.

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...

So I gather you are saying that the fragments of state within a class
Within an instance
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?
Yes, I think so.
>
Also then, what _is_ an "instance variable" ?
Metasyntatic variables:
C - some class
x - some instance
y - the "word" after the dot in the expression: x.y
My working definitions based on my knowledge of Python:

Attribute - y is an attribute of x. Includes instance variables,
properties, and dynamically generated attributes. Since x.y really
ends up doing x.__getattribut e__("y") behind the scenes, overriding
__getattribute_ _ lets you make attribute lookup more dynamic and have
it do interesting things. For example, you could write a class
overriding __getattribute_ _ so that x.y (for any valid Python name y)
opened a file with the name y and returned a file object for this file
(i.e. x.z returns file("z","w"), x.q returns file("q","w"), etc
without enumerating "q", "z", etc anywhere in the class).

Instance variable - In `x.y`, y is an instance variable of x if it's
stored in x.__dict__ or x.__slots__, it's not a method of x (though it
can be a function), and it's not a property.

Property - y is a property if x.y causes a method call and returns the
result of said method call. Basically, x.y becomes equivalent to x.z()
if y is a property. Properties can also allow `x.y = a` to be
equivalent to `x.z(a)` and `del x.y` to be equivalent to `x.z()`.
Properties are created using the built-in function property()

Class variable - Unless you're using metaclasses, in C.y, y is always
a class variable of C. Thus, methods are technically also class
variables. Using metaclasses, C is both a class itself and an instance
of another class D, in which case the definition of "instance
variable" (interpreted with regards to C being an instance of D)
applies to whether y is a class variable of C or not.

Class method - Created using the built-in function classmethod()

Essentially, attribute lookup is very dynamic in Python, which
complicates things a good bit, so the only thing we know for sure
about x.y is that y is an attribute of x.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
>
Thanks,
Roger.

Q: How many pedants does it take to change a lightbulb?
A: Well actually you mean "replace" a lightbulb.
Q: Have you ever kissed a girl?
--
http://mail.python.org/mailman/listinfo/python-list
Nov 21 '08 #9
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
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
that it can hold a reference to an object. A more successful
way of thinking is that the attribute name is associated with the
value. In fact the object typically has a dictionary doing exactly
that, associating attribute names with values. Both the class and
the instance have such dictionaries, although there are a few "specials"
that don't work that way (setattr knows about checking for the
exceptional cases). The "storage" can be removed with the "del"
statement. Try
del d.non_template
print d.non_template
del e.holder
print e.holder

--Scott David Daniels
Sc***********@A cm.Org
Nov 21 '08 #10

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

Similar topics

21
8543
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
2458
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
3178
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
3555
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
9489
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
10356
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
10100
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
9959
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
8988
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...
0
6744
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();...
0
5396
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4061
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
3665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.