"once" assigment in Python

Calvin Spealman ironfroggy at gmail.com
Fri Sep 14 02:44:18 EDT 2007


This is one of the things that I often see people trying to do in
Python, where the best solution is simply to understand how Python
works and craft the code to work with the language. The problem, in my
view, is not that you don't have a good way to do this "once
assignment" operation, but that you are in a position where you don't
know if a name has been assigned to or not. Yes, Python is a very
dynamic language, but that doesn't mean you should exploit this to be
so dynamic that you don't know the state of your own code at a given
point.

If you don't know that a name has been assigned to or not, there are
only a few kinds of structures that lead to such a lack of state
knowledge and all of them are avoidable. A common idiom might go along
the lines of:

if A:
    B = value

Now, if A is false we might not have B defined at all, turning a
condition into an error (a raised NameError if we try to use B. What
we need to do is either find an alternative value, a default value to
assign before all this, or do everything with the value inside the if
block, and not conditionally create names.

There is no good way to do your "once assignment", and that isn't an
accident. Your code is fragile if you don't know what variables you
have. Depending on the type, there are some good solutions. if the
value cannot be None or if its only numbers, for example, you can do
this:

B = B or value

Now it only changes it if B is None or 0, depending on the case. This
may or may not help you. If you use a default None, you can also just
check for that identity explicitly.

On 9/14/07, Lorenzo Di Gregorio <lorenzo.digregorio at gmail.com> 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/



More information about the Python-list mailing list