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

Home Posts Topics Members FAQ

How do I do this? (eval() on the left hand side)

I am new to the Python language.

How do I do something like this:

I know that

a = 3
y = "a"
print eval(y)

would give me a print out of 3 - but how do I do something to the effect of:

eval(y) = 4 # hopefully the value of a gets changed to 4

??

Thanks,

--
It's me
Jul 18 '05 #1
45 2652
Hi It's me

a = 3
y = "a"
print eval(y)


To get 'a' to be 4 here, you would say

a = 4

I am not sure why you would want to do otherwise? Perhaps you could
sketch out a little more about what you are trying to do? That would help
a lot. Are you aiming for something like pointer emulation with simple
datatypes?

Thanks
Caleb
Jul 18 '05 #2

"Caleb Hattingh" <ca****@telkoms a.net> wrote in message
news:op******** ******@news.tel komsa.net...
Hi It's me

a = 3
y = "a"
print eval(y)

To get 'a' to be 4 here, you would say

a = 4


Obviously but that's not what I wish to do.
I am not sure why you would want to do otherwise? Perhaps you could
sketch out a little more about what you are trying to do? That would help
a lot. Are you aiming for something like pointer emulation with simple
datatypes?

In REXX, for instance, one can do a:

interpret y' = 4'

Since y contains a, then the above statement amongs to:

a = 4

There are many situations where this is useful. For instance, you might be
getting an input which is a string representing the name of a variable and
you wish to evaluate the expression (like a calculator application, for
instance).

Thanks
Caleb

Jul 18 '05 #3
Sure, ok, I think I am with you now.

You get a (e.g.) variable name as a string, and you KNOW how to evaluate
it with "eval", but you also want to be able to assign back to (through)
the string representation?

One way (if I understand you correctly) is with the globals or locals
dicts. Try this in IDLE:

'>>> a = 3
'>>> y = 'a'
'>>> eval(y)
3
'>>> d = locals() # Get a dictionary of local variables
'>>> d['a']
3
'>>> d[y]
3
'>>> d[y] = 8 # y is a string = 'a'
'>>> a # The value of a is changed.
8
'>>>

Is this kinda what you mean? I'm still new at this (and don't know REXX
from Adam).

Thanks
Caleb


There are many situations where this is useful. For instance, you
might be
getting an input which is a string representing the name of a variable
and
you wish to evaluate the expression (like a calculator application, for
instance).


Jul 18 '05 #4
"It's me" <it***@yahoo.co m> wrote in message
news:Y0******** ***********@new ssvr14.news.pro digy.com...

In REXX, for instance, one can do a:

interpret y' = 4'

Since y contains a, then the above statement amongs to:

a = 4

There are many situations where this is useful. For instance, you might be getting an input which is a string representing the name of a variable and
you wish to evaluate the expression (like a calculator application, for
instance).


In Python, the canonical advice for this situation is, "Use a dictionary."
This has a number of advantages, including keeping your user's namespace
separate from your application's namespace. Plus it's easier to debug and
maintain the code.

But, if you absolutely, positively have to refer to your variable
indirectly, you could do:

exec "%s = 4" % y

If y refers to the string "a", this will cause the variable a to refer to
the value 4.

--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #5
It's me wrote:
In REXX, for instance, one can do a:

interpret y' = 4'

Since y contains a, then the above statement amongs to:

a = 4


The direct equivalent in Python would be

a = 3
y = 'a'
exec '%s = 4' % y

The better question would be whether or not this as useful as one might
thing in Python; if you find yourself doing this, often there are better
ways to accomplish the same thing, such as using dictionaries.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
But the system has no wisdom / The Devil split us in pairs
-- Public Enemy
Jul 18 '05 #6
On Wed, 2004-12-08 at 05:12, It's me wrote:
There are many situations where this is useful. For instance, you might be
getting an input which is a string representing the name of a variable and
you wish to evaluate the expression (like a calculator application, for
instance).


While I do agree it can be handy, I also think that most possible uses
are also _very_ _dangerous_ security-wise. If possible it'd be safer to
write your code a different way to avoid the evaluation of user-supplied
expressions. For example, you could use a dictionary to store the
'user-accessible' namespace and have all their operations act on that.

You could probably do something _like_ what you want with exec() and
repr, but it'll break as soon as it encounters input that repr can't
make an exec()able string from. It's also really ugly.

If you know what namespace you want to modify ahead of time, or can pass
it to the function doing the modifying, you can also use
getattr()/setattr() or dict methods to do it. For example:
# modify the globals space on the __main__ module
import __main__
varname = 'fred'
setattr(__main_ _, varname, 'blech')
fred 'blech' # same thing
__main__.__dict __[varname] = 'yech!'
fred 'yech!' # modify the attributes of some random object
class dummy(object): .... pass
.... obj = dummy()
setattr(obj, varname, 'eew')
obj.fred 'eew' # same thing using the object's __dict__, NOT RECOMMENDED
# outside the class's own methods.
obj.__dict__[varname] = 'unwise'
obj.fred

'unwise'

This, however, won't do you much good if you don't know what you'll be
modifying. I know the locals() and globals() functions exist, but have
always been leery of the idea of modifying their contents, and am not
sure what circumstances you could do so under even if you felt like
doing so.

In general, it'll be _much_ safer to use a generic object with
getattr/setattr or a dict than to try to work with your local or global
namespaces like this...

--
Craig Ringer

Jul 18 '05 #7
It's me wrote:
How do I do something like this:

I know that

a = 3
y = "a"
print eval(y)

would give me a print out of 3 - but how do I do something to the effect of:

eval(y) = 4 # hopefully the value of a gets changed to 4


Generally, if you find yourself doing this, you may want to rethink your
program organization. That being said, if you are in the global scope,
one option looks something like:
a = 3
y = 'a'
globals()[y] = 4
a

4

If you can give us some more context on why you want to do this, we can
probably suggest a better approach. There aren't too many places where
even advanced Python programmers need to use eval...

Steve
Jul 18 '05 #8
Yes, Russell, what you suggested works.

I have to chew more on the syntax to see how this is working.

because in the book that I have, it says:

exec code [ in globaldict [, localdict] ]

....

--
It's me
"Russell Blau" <ru******@hotma il.com> wrote in message
news:31******** *****@individua l.net...
"It's me" <it***@yahoo.co m> wrote in message
news:Y0******** ***********@new ssvr14.news.pro digy.com...

In REXX, for instance, one can do a:

interpret y' = 4'

Since y contains a, then the above statement amongs to:

a = 4

There are many situations where this is useful. For instance, you might
be
getting an input which is a string representing the name of a variable

and you wish to evaluate the expression (like a calculator application, for
instance).


In Python, the canonical advice for this situation is, "Use a dictionary."
This has a number of advantages, including keeping your user's namespace
separate from your application's namespace. Plus it's easier to debug and
maintain the code.

But, if you absolutely, positively have to refer to your variable
indirectly, you could do:

exec "%s = 4" % y

If y refers to the string "a", this will cause the variable a to refer to
the value 4.

--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.

Jul 18 '05 #9
Thanks for all the replies and yes I realize the associated issue of doing
something like this.

For simplicity sake, let's say I need to do something like this (for
whatever reason):

<prompt for name of variable in someother program space you wish to
retrieve>
<go retrieve the value from that other program>
<assign the retrieved value to a variable of the same name in Python>

In situations like this, I wouldn't know the name of the variable in Python
I need to use ahead of time and so I would have to somehow convert a string
to be used as variable. Of course, I can create a dictionary to keep track
of which variable has what name and this method of using exec should be
avoid if at all possible.

I am just trying to understand the language and see what it can do.

--
It's me


"Steven Bethard" <st************ @gmail.com> wrote in message
news:Ypptd.1529 96$V41.76678@at tbi_s52...
It's me wrote:
How do I do something like this:

I know that

a = 3
y = "a"
print eval(y)

would give me a print out of 3 - but how do I do something to the effect of:

eval(y) = 4 # hopefully the value of a gets changed to 4


Generally, if you find yourself doing this, you may want to rethink your
program organization. That being said, if you are in the global scope,
one option looks something like:
>>> a = 3
>>> y = 'a'
>>> globals()[y] = 4
>>> a

4

If you can give us some more context on why you want to do this, we can
probably suggest a better approach. There aren't too many places where
even advanced Python programmers need to use eval...

Steve

Jul 18 '05 #10

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

Similar topics

10
6170
by: Cybertof | last post by:
Hello, Do you know why i get the error "Left hand side must be variable, property or indexer" with the following code : struct FundDataStruct { internal int quantity;
4
12461
by: =?Utf-8?B?UmljaA==?= | last post by:
Hello, Is there a setting/property for displaying a checkbox label (or radiobutton label) on the left hand side instead of the right hand side? Or am I limited to no text in the label - take on parent backcolor and add my own label to the left side? Thanks, Rich
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
7920
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
8401
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...
0
8268
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...
1
5867
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...
0
3900
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
2418
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
0
1254
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.