473,320 Members | 1,939 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,320 software developers and data experts.

naming objects from string

Hi,

If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)

and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?

Sep 21 '06 #1
16 1276
manstey wrote:
Hi,

If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)

and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?
Depends on your namespace, but for the local namespace, you can use this:

pya = object()
pya
<object object at 0x40077478>
pylocals()['bob'] = a
pybob
<object object at 0x40077478>

A similar approach can be used for the global namespace.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 21 '06 #2
Hi,

But this doesn't work if I do:

a=object()
x='bob'
locals()[x] = a

How can I do this?

James Stroud wrote:
manstey wrote:
Hi,

If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)

and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?

Depends on your namespace, but for the local namespace, you can use this:

pya = object()
pya
<object object at 0x40077478>
pylocals()['bob'] = a
pybob
<object object at 0x40077478>

A similar approach can be used for the global namespace.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 21 '06 #3
manstey wrote:
If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)

and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?
Direct answer:
Look up the setattr() functions (DO look it up!). Replace your
name(b) = a line with
setattr(__builtins__, a, b).
There you go.
Hopefully more helpful answer:
One alternative would be using a dictionary. Your example would then
translate to:

a = 'hello'
b = (1234,) # notice the comma!
# without it, it wouldn't be a tuple but a simple
# parenthesized integer
d = {} # your dictionary

d[a] = b # assign the value of b to a key given by a

d[a]
>>(1234,)
d['hello']
>>(1234,)
In most cases this will be a LOT less cumbersome compared to messing
with module attributes.

hope that helps a bit
wildemar
Sep 21 '06 #4
manstey wrote:
Hi,

But this doesn't work if I do:

a=object()
x='bob'
locals()[x] = a

How can I do this?
try
sys.modules[__name__].__dict__[x] = a

But what's the point?
--
damjan
Sep 21 '06 #5
manstey wrote:
Hi,

But this doesn't work if I do:

a=object()
x='bob'
locals()[x] = a

How can I do this?
You can. I just copy/pasted your code and it works fine here. (You are
aware that there is whitespace before locals() that you have to remove
before you feed it to the snake?)

What error did you get?

Let me again stress that using locals and globals is a bit contrived,
whereas the dictionary approach from my other post is not.
Just out of curiosity: Why do you want to do this anyway?

wildemar
Sep 21 '06 #6
Damjan wrote:
try
sys.modules[__name__].__dict__[x] = a
@manstay: You see! Ugly, unreadable trickery!
Hands off this stuff, bad mojo!

You've been told three very different approaches now, which is a pretty
good indicator that there is no obvious way to do it. Which means
another angle to your problem might make it a lot easier.
(btw: Try 'import this' at the python prompt for some wise words.)

Please describe your problem and let us suggest that new angle.

wildemar
Sep 21 '06 #7
Hi,

thanks for the suggestions. this is my problem:

I have a metadata file that another user defines, and I don't know
their structure in advance. They might have 300+ structures. the
metadata defines the name and the tuple-like structure when read by
python.

my program reads in the metadata file and then generates python tuples
corresponding to their structures.

so they might provide a list of names, like 'bob','john','pete', with 3
structures per name, such as 'apple','orange','red' and I need 9 tuples
in my code to store their data:

bob_apple=()
bob_orange=()
...
pete_red=()

I then populate the 9 tuples with data they provide in a separate file,
and the filled tuples are then validated against the metadata to make
sure they are isomorphic.

Is this clear?

thanks

Sep 21 '06 #8
Hi,

thanks for the suggestions. this is my problem:

I have a metadata file that another user defines, and I don't know
their structure in advance. They might have 300+ structures. the
metadata defines the name and the tuple-like structure when read by
python.

my program reads in the metadata file and then generates python tuples
corresponding to their structures.

so they might provide a list of names, like 'bob','john','pete', with 3
structures per name, such as 'apple','orange','red' and I need 9 tuples
in my code to store their data:

bob_apple=()
bob_orange=()
...
pete_red=()

I then populate the 9 tuples with data they provide in a separate file,
and the filled tuples are then validated against the metadata to make
sure they are isomorphic.

Is this clear?

thanks

Sep 21 '06 #9
manstey wrote:
Hi,

thanks for the suggestions. this is my problem:

I have a metadata file that another user defines, and I don't know
their structure in advance. They might have 300+ structures. the
metadata defines the name and the tuple-like structure when read by
python.

my program reads in the metadata file and then generates python tuples
corresponding to their structures.

so they might provide a list of names, like 'bob','john','pete', with 3
structures per name, such as 'apple','orange','red' and I need 9 tuples
in my code to store their data:

bob_apple=()
bob_orange=()
..
pete_red=()

I then populate the 9 tuples with data they provide in a separate file,
and the filled tuples are then validated against the metadata to make
sure they are isomorphic.

Is this clear?
Erm, not exactly but I think I get it.

Note that creating empty tuples will mean that they will always be
empty. They are immutable, basically meaning that you can not change
them after they are created. If you want to create empty data that you
want to fill later on, use lists. Or (which might be more convenient)
put in the data right away).

Generally, since you do not know the names ('bob', 'john', etc.) and the
structures in advance, the best way to store them is in a *variable*.
Here I would suggest dictionaries again. Let me write an example in
pseudo python:

people = {} # data dict
# lets suppose the data from your file is a list of tuples like:
# [('bob',('orange', 'apple', 'red')), ...]
# (I didnt quite get how your data is organized)
for name, structure in list_of_names_from_file:
people[name] = {} # make a new dict for the 'structures'
for item in structure:
people[name][item] = () # empty tuple
# instead of an empty tuple you could fill in your data
# right here, which would save you the extra keyboard mileage

Does that make sense in the context of your application?

wildemar
Sep 21 '06 #10
"manstey" <ma*****@csu.edu.auwrites:
If I have a string, how can I give that string name to a python
object, such as a tuple.
The thing I'd like to know before answering this is: how will you be
using that name to refer to the object later?

--
\ "If you ever catch on fire, try to avoid seeing yourself in the |
`\ mirror, because I bet that's what REALLY throws you into a |
_o__) panic." -- Jack Handey |
Ben Finney

Sep 21 '06 #11
"manstey" <ma*****@csu.edu.auwrote:
>
If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)
That's not a tuple. That's an integer. (1234,) is a tuple.
>and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?
Yes, but it's almost never the right way to solve your problem. Use an
explicit dictionary instead.

C:\Tmp>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>a='hello'
locals()[a] = 1234
hello
1234
>>>
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Sep 21 '06 #12
At Thursday 21/9/2006 00:59, manstey wrote:
>If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)

and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?
You may use another object as a namespace:

class X: pass
x = X()

a = 'hello'
b = (1,2,3,4)
setattr(x, a, b)

print x.hello # prints (1,2,3,4)
getattr(x, a) # returns the same

but perhaps if you explain better what you want, we can figure out
how to do that...

Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Sep 21 '06 #13
manstey wrote:
so they might provide a list of names, like 'bob','john','pete', with 3
structures per name, such as 'apple','orange','red' and I need 9 tuples
in my code to store their data:

bob_apple=()
bob_orange=()
..
pete_red=()

I then populate the 9 tuples with data they provide in a separate file,
and the filled tuples are then validated against the metadata to make
sure they are isomorphic.
if you want a dictionary, use a dictionary.

</F>

Sep 21 '06 #14
manstey wrote:
so they might provide a list of names, like 'bob','john','pete', with 3
structures per name, such as 'apple','orange','red' and I need 9 tuples
in my code to store their data:

bob_apple=()
bob_orange=()
..
pete_red=()
I really think you should be using dictionaries here. You don't want to be
messing around creating random variables in the local or global namespace.

For instance

myvals = {}
myvals['bob'] = {}
myvals['pete'] = {}
....
myvals['bob']['apple'] = (1,2,3,4)
myvals['bob']['orange'] = (2,3,4)
myvals['pete']['red'] = (4,5,6,7)

and so on
>>myvals
{'pete': {'red': (4, 5, 6, 7)}, 'bob': {'orange': (2, 3, 4), 'apple': (1, 2,
3,4)}}

--
Jeremy Sanders
http://www.jeremysanders.net/
Sep 21 '06 #15

"James Stroud" <js*****@mbi.ucla.eduwrote in message
news:zv*****************@newssvr13.news.prodigy.co m...
Depends on your namespace, but for the local namespace, you can use this:

pya = object()
pya
<object object at 0x40077478>
pylocals()['bob'] = a
pybob
<object object at 0x40077478>
If you put this code within a function, it probably will not work.
locals() is usually a *copy* of the local namespace and writes do not write
back to the namespace itself.

tjr

Sep 21 '06 #16
manstey wrote:
[...]
bob_apple=()
bob_orange=()
..
pete_red=()

I then populate the 9 tuples with data [...]
You cannot "populate" a tuple. If you want to insert the values
individually, you have to use a list. If you insert them all together,
like this: bob_apple = (1, 2, ..., 9), you don't need to initialize
bob_apple with an empty tuple.

--
Roberto Bonvallet
Sep 21 '06 #17

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

Similar topics

4
by: VK | last post by:
09/30/03 Phil Powell posted his "Radio buttons do not appear checked" question. This question led to a long discussion about the naming rules applying to variables, objects, methods and properties...
14
by: 42 | last post by:
Hi, Stupid question: I keep bumping into the desire to create classes and properties with the same name and the current favored naming conventions aren't automatically differentiating them......
8
by: Lance | last post by:
I've been teaching myself C# for a few months now and I have a concept problem. I know how to instantiate an object from a class I’ve created, but now I want to retrieve and store data in a...
6
by: dm1608 | last post by:
I'm relatively new to ASP.NET 2.0 and am struggling with trying to find the best naming convention for the BAL and DAL objects within my database. Does anyone have any recommendations or best...
3
by: rsine | last post by:
I have searched around a little and have yet to find a naming convention for the string builder object. I really do not want to use "str" since this is for string objects and thus could be...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.