473,602 Members | 2,746 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with dynamic attributes.

Hi all,
I was writing a simple class when I get a strange error message that I
can't
understand. Hopefully someone could help me here.

My class's init method takes a list of lists as input argument and I'd
like to create
several attributes each one referencing one item of the passed list.
Easy-of-use arguments
has led me to call these attributes as x0, x1, x2 and so on. In order
to get as many
attributes as the number of items of the passed list dynamically
defined I wrote the
following code:

class foo(object):
def __init__(self, list_of_lists):
self.lol = list(list_of_li sts)

for i in range(len(list_ of_lists)):
exec 'self.x%d = self.lol[%d]' % (i, i)

self.shape = tuple(len(item) for item in self.lol)

As soon as I try to import the module in which this class is defined I
get the following
error message:

SyntaxError: unqualified exec is not allowed in function '__init__' it
contains a nested
function with free variables (module_name.py , line 49)

After a little bit of trials and errors I found that if I comment out
the line

self.shape = tuple(len(item) for item in self.lol)

or I rewrote the for cycle as follows:

for i in range(len(list_ of_lists)):
exec 'self.x%d = self.lol[%d]' % (i, i) in locals()

the error disappears and the code works as expected. What it is even
more strange to me is
that if I replace the generator expression statement (that defines
self.shape) with an
explicit for-loop the error message doesn't come in and the code works
flawlessly.

I really can't understand why it happens and I'm wondering what it's
going on here behind
the scene. Any explanation? Any better way to get the same attributes I
got with the exec
statement?

Thanks in advance,
Andrea

Jan 9 '06 #1
4 1298
"Mr.Rech" wrote:
class foo(object):
def __init__(self, list_of_lists):
self.lol = list(list_of_li sts)

for i in range(len(list_ of_lists)):
exec 'self.x%d = self.lol[%d]' % (i, i)

self.shape = tuple(len(item) for item in self.lol)
generator expressions are anonymous functions, and the "self" in that line
is a free variable (that is, it belongs to an outer scope). Python uses static
analysis to identify free variables, and that doesn't mix well with exec.
Any better way to get the same attributes I got with the exec statement?


use setattr(self, name, value)

</F>

Jan 9 '06 #2
I would have sworn that it had been a better way to get it.

Thanks a lot,
Andrea

Jan 9 '06 #3
Mr.Rech a écrit :
(snip)

My class's init method takes a list of lists as input argument and I'd
like to create
several attributes each one referencing one item of the passed list.

Easy-of-use arguments
has led me to call these attributes as x0, x1, x2 and so on.


This is a very wrong design IM(ns)HO. A 'has-many' semantic is better
expressed by a multivalued attribute (ie : list, tuple or dict) than by
an undefined number of monovalued attributes. Also, the way you're
trying to implement it, you will loose sync between individual
monovalued attributes and the list of lists.

My 2 cents
Jan 9 '06 #4
"Mr.Rech" <an************ *@gmail.com> writes:
Hi all,
I was writing a simple class when I get a strange error message that I
can't
understand. Hopefully someone could help me here.

My class's init method takes a list of lists as input argument and I'd
like to create
several attributes each one referencing one item of the passed list.


Why? You save all of two characters per reference over doing a simple

self.x = list(self.lol)

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jan 10 '06 #5

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

Similar topics

7
1576
by: Snake | last post by:
Hi guys, I have question about classes. when u create class called Test. and you define variable Test c; so does this act like( a variable c of type Test pointing to an abject )? The thing that I am confused with java where you say Test c = new Test; whre you can move this Test object around by saying "Test b" and then b = c;(so c and b points to the same object). while in c++ I think it has different meaning(like b would have different...
1
4231
by: Rohit Raghuwanshi | last post by:
Hello all, we are running a delphi application with DB2 V8.01 which is causing deadlocks when rows are being inserted into a table. Attaching the Event Monitor Log (DEADLOCKS WITH DETAILS) here. From the log it looks like the problem happens when 2 threads insert 1 record each in the same table and then try to aquire a NS (Next Key Share) lock on the record inserterd by the other thread. Thanks Rohit
0
2639
by: David J | last post by:
Hi, I am strugling with the propertygrid and a listbox. I am using the universaldropdowneditor from the codeproject (code below). However I am populating the listbox via a datasource. The problem I am having is that when I have a value in the propertygird and edit that, I want the listbox to have the selectvalue equal to the value that is being edited. Just to make it clearer: PropgridVal = Germany Datasource=
3
1704
by: Dave Rose | last post by:
Hello all. I was wondering if creating classes could be dynamic. I want to know if I can make a class Person, then read in a list of names (say people's names) so then I can have a class instance created for each name in the list? Why do I want to do this? I was just thinking if I had a name on the list, Dave, I could then be able to read the name in the list, and assign Maria.birthday = <> and all the other attributes I would want to...
2
2697
by: WolfyUK | last post by:
Hello, I have a standard asp:DataGrid called CasesGrid that I wish to write my own paging controls for. The aim is to get something like the following rendered to screen: << First < Previous 1 2 3 4 5 ... Next Last >> I have achieved the first/previous/next/last buttons quite easily as follows in the ASPX (1.1) page:
0
5546
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
4
4204
by: coconet | last post by:
Server is Win2K3/IIS6. I have an ASPX page with this in the <headtag: <link rel="stylesheet" type="text/css" href="<% Response.Write( "http://" + Request.ServerVariables.ToString() + this.ResolveUrl("~") + "styles/styledefault.aspx"); %>" />
3
2931
by: =?Utf-8?B?U3ViYQ==?= | last post by:
I am using a asp page to dynamically create a stylesheet my asp page creates the following css element when i call the asp page my typing the url in the browser. My asp page works fine............ body { font-family : Arial, Helvetica, Sans-Serif, Verdana ; margin : 0 ; padding : 0 ; }
0
1409
by: Sundhas | last post by:
Hey! Scenario:What my project do right now 1. User Enters his Login and Password through his mobile phone and servlets contacts webservice of Authentication and user gets authenticated with the system in the mean while user is Authorized also i.e What page he is allowed to see. 2. Page appears infront of user on his mobile screen from where he can select the attributes as well as the type of report he wants to view....
0
7993
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, 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...
0
8405
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...
0
8404
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 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...
1
8056
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
8270
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
5440
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
3901
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
2424
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
1
1511
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.