473,407 Members | 2,629 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,407 software developers and data experts.

programmatically define a new variable on the fly

Hi,

I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing. So, for example, if I the file
I'm reading has
g 99
on the first line, I want to create a new variable called "Xg" whose
length
is 99.
I tried eval("Xg=[0]*99") but that did not work.

any help would be greatly appreciated
Lee

Aug 9 '07 #1
7 5777
On Aug 9, 5:11 pm, Lee Sander <lesa...@gmail.comwrote:
Hi,

I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing. So, for example, if I the file
I'm reading has
g 99
on the first line, I want to create a new variable called "Xg" whose
length
is 99.
I tried eval("Xg=[0]*99") but that did not work.
eval only evaluates expressions. To go about the problem that way, you
would use exec, not eval.

Of course, use of exec generally means you're going about the problem
the wrong way; it looks to me like a better way to do what you're
doing is to create a dictionary to hold your values. So, given the
variables data (the dictionary), name (in your example, 'g') and
*size* (in your example, 99), you can add it data as shown:

data[name] = [0]
data[name] *= size

Note that by splitting the '[0]*size' code into two lines as shown
above, you don't create an intermediate list object that gets thrown
away right after creation.

Aug 9 '07 #2
On Aug 9, 5:30 pm, Dustan <DustanGro...@gmail.comwrote:
given the
variables data (the dictionary), name (in your example, 'g') and
*size* (in your example, 99), you can add it data as shown:
erm... make that:

given the variables data (the dictionary), name (in your example, 'g')
and size (in your example, 99), you can add it to data as shown:

Aug 9 '07 #3
Lee Sander wrote:
Hi,

I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing. So, for example, if I the file
I'm reading has
g 99
on the first line, I want to create a new variable called "Xg" whose
length
is 99.
I tried eval("Xg=[0]*99") but that did not work.

any help would be greatly appreciated
Lee
>>Xg
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Xg' is not defined
>>namespace = globals()
var_name = 'Xg'
var_value = [0] * 9
namespace[var_name] = var_value
Xg
[0, 0, 0, 0, 0, 0, 0, 0, 0]

Ian

Aug 9 '07 #4
On Aug 9, 6:11 pm, Lee Sander <lesa...@gmail.comwrote:
I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing.
Use a dictionary.

Aug 9 '07 #5
Lee Sander a écrit :
Hi,

I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing. So, for example, if I the file
I'm reading has
g 99
on the first line, I want to create a new variable called "Xg" whose
length
is 99.
I tried eval("Xg=[0]*99") but that did not work.

any help would be greatly appreciated
As others already pointed out, the canonical solution is to use a dict,
and it's almost always the best solution - a variant being to use an
object (eventually a module object) and dynamically add attributes to it
using setattr()[1].

Now, for the corner case where you *really* want to dynamically create
new names in the module itself, the solution is to use exec. But I would
definitively *not* recommand this solution unless you really know what
you're doing and why you're doing it.

For the record, I did use this last solution twice in seven years. And
it was mostly to avoid repeating boilerplate code in some low-level
module of a framework. Definitively not a common case...
[1] which, FWIW, doesn't make much differences since attributes are
stored in dicts....
Lee
Aug 10 '07 #6
On 10 ago, 00:11, Lee Sander <lesa...@gmail.comwrote:
Hi,

I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing. So, for example, if I the file
I'm reading has
g 99
on the first line, I want to create a new variable called "Xg" whose
length
is 99.
I tried eval("Xg=[0]*99") but that did not work.
>>letter = 'g'
import __main__
setattr(__main__,'X%s'%letter,[0]*99)
Xg
[0, 0, 0 ...

Anyway, I donīt see the point in this. Why donīt you just use
something like X['g'] instead?

Aug 10 '07 #7
Anyway, I donīt see the point in this. Why donīt you just use
something like X['g'] instead?
While it's not what the original author is intending, it seems to me
that dynamically adding fields could be useful when something like a
database schema changed frequently. For example, a row in a database
might contain data related to a customer and I would think it might be
useful to do something like this (where data is a dictionary created
from the column names and row data):

class Customer:
def __init__(self, data):
for col_name, value in data.iteritems():
setattr(self, col_name, value)

Alternatively, you could just assign the original dictionary to a
field on Customer called data and then access it by key:

class Customer:
def __init__(self, data):
self.customerData = data

I'm pretty new to Python so it's entirely possible I'm doing things
the hard way but if you had behavior on a class, I can see where
dynamically creating fields on it would be useful.
Aug 13 '07 #8

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

Similar topics

1
by: Alex | last post by:
How I can programmatically define the name of namespace and the name of class? using System; namespace MyNamespace { class MyClass {
1
by: Martine | last post by:
Hi there! I have a problem with programmatically adding user controls to my mobile webforms. If I load my usercontrol programmatically (in the Page_Load), the object is instantiated, I have...
4
by: Shaul Feldman | last post by:
Hello, I have something really awkward at work - fighting with CheckBoxList... How can I define CSS for ListItem in CheckBoxList programmatically. I add CheckBoxList's Items on the fly, something...
9
by: Rob Meade | last post by:
Hi all, I have a form which is programmatically created from reading values from a database table. There is a 'form' for each DocumentType - when I say form I mean as in a different form will...
1
by: BobAchgill | last post by:
When I try to change the Color.Lime with a string that contains the contents "Color.Lime" I get a Casting compile error. So how can I get past this casting issue to change out the color...
0
by: TB | last post by:
Hi All: I have this page where a rows / cells are programmatically added to to table by pushing a button. The rows contain a textbox and a associated button. What I want to is to be able to...
4
by: Bob | last post by:
Hi, I'm working with VWD and i defined programmatically a button (in code-behind) with an ID. So I expect to see beside "Page Events" and "Form1" my button "b1" in order to use the Click event....
1
by: kimkamp | last post by:
I want to create a variable name programmatically. For instance: Dim GlobVar as String = "My.STL." Dim VarName as String = "sAccountNo" Dim VarValue as String = "ABC123" I want to end up...
0
by: Peter Afonin | last post by:
Hello, I'm still learning Crystal reports, and now I need to sort report programmatically. I've found a good article about it:...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...

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.