473,796 Members | 2,560 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"once" assigment in Python

Hello,

I've been using Python for some DES simulations because we don't need
full C speed and it's so much faster for writing models. During
coding I find it handy to assign a variable *unless it has been
already assigned*: I've found that this is often referred to as "once"
assigment.

The best I could come up with in Python is:

try:
variable
except NameError:
variable = method()

I wonder if sombody has a solution (trick, whatever ...) which looks
more compact in coding. Something like:

once(variable, method)

doesn't work, but it would be perfect. Of course I can preprocess the
Python code but an all-Python solution would be more handy.

Any suggestions?

Thx in advance,
Lorenzo

Sep 14 '07 #1
10 1511
In message <11************ *********@w3g20 00hsg.googlegro ups.com>, Lorenzo Di
Gregorio wrote:
During coding I find it handy to assign a variable *unless it has been
already assigned*: I've found that this is often referred to as "once"
assigment.
Why not just assign to it once at the beginning and be done with it?
Sep 14 '07 #2
Lorenzo Di Gregorio wrote:
Hello,

I've been using Python for some DES simulations because we don't need
full C speed and it's so much faster for writing models. During
coding I find it handy to assign a variable *unless it has been
already assigned*: I've found that this is often referred to as "once"
assigment.

The best I could come up with in Python is:

try:
variable
except NameError:
variable = method()

I wonder if sombody has a solution (trick, whatever ...) which looks
more compact in coding. Something like:

once(variable, method)

doesn't work, but it would be perfect. Of course I can preprocess the
Python code but an all-Python solution would be more handy.

Any suggestions?
Without being fatuous, I would suggest you rethink your approach to the
problem.

Do your variables have default values? If not, what happens if the user
does not set them and your code tries to refer to them? You seem to be
trying to apply defaults if the user hasn't set a value, when the
correct things to do is to apply the defaults *before the user gets a
chance to do anything at all*. Then any changes made by the user will
overwrite the defaults.

Even better, if its practical, is to provide your functionality as one
or more functions, whose definitions can set default values for keyword
arguments.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

Sep 14 '07 #3
Lorenzo Di Gregorio wrote:
I've been using Python for some DES simulations because we don't need
full C speed and it's so much faster for writing models. During
coding I find it handy to assign a variable *unless it has been
already assigned*: I've found that this is often referred to as "once"
assigment.

The best I could come up with in Python is:

try:
variable
except NameError:
variable = method()

I wonder if sombody has a solution (trick, whatever ...) which looks
more compact in coding. Something like:

once(variable, method)

doesn't work, but it would be perfect. Of course I can preprocess the
Python code but an all-Python solution would be more handy.

Any suggestions?
You can use properties to implement lazy evaluation. Or you can rely on a
naming convention:
>>class Once(object):
.... def __getattr__(sel f, name):
.... if name.startswith ("_calc_"):
.... raise AttributeError( "No method to calculate attribute %r" % name[6:])
.... value = getattr(self, "_calc_" + name)()
.... setattr(self, name, value)
.... return value
....
>>class A(Once):
.... def _calc_foo(self) :
.... print "calculatin g foo"
.... return 42
....
>>a = A()
a.foo
calculating foo
42
>>a.foo
42
>>a.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __getattr__
File "<stdin>", line 4, in __getattr__
AttributeError: No method to calculate attribute 'bar'
>>a._calc_bar = lambda: "bar-value"
a.bar
'bar-value'

Peter
Sep 14 '07 #4
Agree that what you are looking for may not be a good idea. So make
sure you don't shoot yourself in the foot with it. You should
probably look into your problem some more.
>>def once(obj,attrna me,value):
.... if hasattr(obj,att rname):
.... return
.... else:
.... setattr(obj,att rname,value)
....
>>class Foo:
.... pass
....
>>foo = Foo()
once(foo,"a", 1)
foo.a
1
>>once(foo,"b", 2)
foo.a
1
>>def m1(self):
.... print "i am m1"
....
>>def m2(self):
.... print "i am m2"
....
>>once(Foo,"mx" ,m1)
foo.mx()
i am m1
>>once(Foo,"mx" ,m2)
foo.mx()
i am m1
>>>
This is very generic code, but you could make it specific to a class
and an attribute. If so look into properties.

class Foo2:

def _setMyAttr(self ,value):
if hasattr(self,"_ myAttr"):
return
self._myAttr = value

def _getMyAttr(self ):
if not hasattr(self,"_ myAttr"):
return "somedefaultval ue"
return self._myAttr

myAttr = property(_getMy Attr,_setMyAttr )

Note also : stay away from __setattr__ until you know what you are
doing and
you know when to use self.__dict__ assignments. Painful personal
experiences for me.

Sep 14 '07 #5
On Fri, 14 Sep 2007 06:16:56 +0000, Lorenzo Di Gregorio wrote:
Hello,

I've been using Python for some DES simulations because we don't need
full C speed and it's so much faster for writing models. During coding
I find it handy to assign a variable *unless it has been already
assigned*: I've found that this is often referred to as "once"
assigment.
I could see reasons for doing something like this at a module level or
for attributes; such as setting default values when defaults are
expensive to calculate. You could, as others have said, initialize the
variable to a trivial value and then test whether it still held the
trivial value later, but what's the point?

The best I could come up with in Python is:

try:
variable
except NameError:
variable = method()

I wonder if sombody has a solution (trick, whatever ...) which looks
more compact in coding. Something like:

once(variable, method)

doesn't work, but it would be perfect.
For module level variables you can do something like this:

def once(symbol,met hod):
g = globals()
if symbol not in g:
g[symbol] = method()

You'd have to pass a symbol as a string, but that's no big deal.

For local variables you're stuck with trying to catch UnboundLocalErr or.
There's a way to do it by examining stack frames, but I don't really
recommend it: it's inefficient, and the once assignment doesn't make as
much sense for local variables.

Carl Banks
Sep 14 '07 #6
Thank you very much for your suggestions!
I'll try in the next days to elaborate a bit on the last two ones.

By the way, the "once" assignment is not that evil if you use it for
hardware modeling.
Most hardware models look like:

wire1 = function()
instance component(input =wire1,output=w ire2)
result = function(wire2)

When employing Python it's pretty straightforward to translate the
instance to an object.

instance = Component(input =wire1,output=w ire2)

Then you don't use "instance" *almost* anymore: it's an object which
gets registered with the simulator kernel and gets called by reference
and event-driven only by the simulator kernel. We might reuse the
name for calling some administrative methods related to the instance
(e.g. for reporting) but that's a pretty safe thing to do. Of course
all this can be done during initialization, but there are some good
reasons (see Verilog vs VHDL) why it's handy do be able to do it
*anywhere*. The annoying problem was that every time the program flow
goes over the assignment, the object gets recreated.

Indeed Python itself is not a hardware modeling language, but I built
some infrastructure to fill what I was missing and for quickly
building up a functional prototype and testing some ideas Python is
really excellent.

Best Regards,
Lorenzo

Sep 14 '07 #7
Lorenzo Di Gregorio <lo************ ****@gmail.comw rote:
When employing Python it's pretty straightforward to translate the
instance to an object.

instance = Component(input =wire1,output=w ire2)

Then you don't use "instance" *almost* anymore: it's an object which
gets registered with the simulator kernel and gets called by reference
and event-driven only by the simulator kernel. We might reuse the
name for calling some administrative methods related to the instance
(e.g. for reporting) but that's a pretty safe thing to do. Of course
all this can be done during initialization, but there are some good
reasons (see Verilog vs VHDL) why it's handy do be able to do it
*anywhere*. The annoying problem was that every time the program flow
goes over the assignment, the object gets recreated.
If you originally set, e.g.,

instance = None

then using in your later code:

instance = instance or Component(...)

will stop the multiple creations. Other possibilities include using a
compound name (say an.instance where 'an' is an instance of a suitable
container class) and overriding the __new__ method of class Component so
that it will not return multiple distinct objects with identical
attributes. "Has this *plain* name ever been previously assigned to
anything at all" is simply not a particularly good condition to test for
(you COULD probably write a decorator that ensures that all
uninitialized local variables of a function are instead initialized to
None, but I'd DEFINITELY advise against such "black magic").
Alex
Sep 14 '07 #8
Lorenzo Di Gregorio wrote:
Hello,

I've been using Python for some DES simulations because we don't need
full C speed and it's so much faster for writing models. During
coding I find it handy to assign a variable *unless it has been
already assigned*: I've found that this is often referred to as "once"
assigment.

The best I could come up with in Python is:

try:
variable
except NameError:
variable = method()

I wonder if sombody has a solution (trick, whatever ...) which looks
more compact in coding. Something like:

once(variable, method)

doesn't work, but it would be perfect. Of course I can preprocess the
Python code but an all-Python solution would be more handy.

Any suggestions?

Thx in advance,
Lorenzo
IMHO variables like what you describe are really data not program variables.
You might consider putting variables like these in a dictionary and then check
to see if the keys exist before assignment:

var_dict={}

#
# See if 'varname' initialized, if not it needs to be
#
if 'varname' not in var_dict:
var_dict[varname]=somevalue

-Larry
Sep 17 '07 #9
On 17 Sep., 16:54, Larry Bates <larry.ba...@we bsafe.comwrote:
>
IMHO variables like what you describe are really data not program variables.
You might consider putting variables like these in a dictionary and then check
to see if the keys exist before assignment:

var_dict={}

#
# See if 'varname' initialized, if not it needs to be
#
if 'varname' not in var_dict:
var_dict[varname]=somevalue
This is a good point!

I could write something like:

instantiate('co mponent',functi on)

and have instantiate() to conditionally do:

instance['component']=Module(functio n)

Of course this means using:

instance['component'].method()

instead of just:

component.metho d()

A more annoying difficulty is with the fact that, while the scope of
ordinary variables is limited (function, package), the scope of
'component' would be global (the whole instance[]): having global
names could be pretty annoying in modeling a hierarchy. Anyway, some
scoping mechanism could be implemented over the global dictionary and
this could be a good price to pay to avoid other tricks.
Further suggestions?

Thank you!
Lorenzo

Sep 17 '07 #10

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

Similar topics

2
1406
by: dam_fool_2003 | last post by:
Friends, I come across a resent thread describes the differences between getc() vs fgetc(). There some body stated the sentence "evaluate its parameter more than once". I cannot understand the word ‘evaluate' in the message. The poster also gives a Example for the sentence, which is hard for me to understand. I searched the FAQ and I think I have missed it. The thread's link is:
7
1900
by: Petr Jakes | last post by:
I would like to do "some action" once a minute. My code (below) works, I just wonder if there is some more pythonic approach or some "trick" how to do it differently. minutes=time.localtime() while 1: min, sec = time.localtime() if sec==0 and minutes!=min: # first occur of sec==0 only!! polling 10x a second minutes=min
187
6560
by: Lasse Espeholt | last post by:
Hi... I am relativ new to the impressive and powerfull C language, but i thinks it is obsolete... The idea with header/source files where methods can clash into eachother i don't like... Look at C# which is much cleaner with namespaces. Why has C not namespaces and a "area idea" where some methods and
1
1938
by: anupam | last post by:
Can anybody please tell me what is #pragma once and why compiler gives "lvalue requirement" errors :confused:
0
9684
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
9530
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
10236
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
10182
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
10017
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
9055
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
5445
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...
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.