Python's "only one way to do it" philosophy isn't good?
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sat Jun 23 14:36:12 EDT 2007
On Sat, 23 Jun 2007 12:39:51 -0400, Douglas Alan wrote:
> One of the things that annoys me when coding in Python (and this is a
> flaw that even lowly Perl has a good solution for), is that if you do
> something like
>
> longVarableName = foo(longVariableName)
>
> You end up with a bug that can be very hard to track down. So one use
> for macros would be so that I can define "let" and "set" statements so
> that I might code like this:
>
> let longVariableName = 0
> set longVarableName = foo(longVariableName)
>
> Then if longVarableName didn't already exist, an error would be
> raised, rather than a new variable being automatically created for me.
So "let" is the initial declaration, and "set" modifies the existing
variable?
What happens is you declare a variable twice?
let longVariableName = 0
let longVariableName = foo(longVariableName) # oops I meant set
How long did it take you to write the macros, and use them, compared to
running Pylint or Pychecker or equivalent?
But if you really want declarations, you can have them.
>>> import variables
>>> variables.declare(x=1, y=2.5, z=[1, 2, 4])
>>> variables.x = None
>>> variables.w = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "variables.py", line 15, in __setattr__
raise self.DeclarationError("Variable '%s' not declared" % name)
variables.DeclarationError: Variable 'w' not declared
The variables module isn't part of the standard library. Here's the code
for it:
import sys
class _variable:
class DeclarationError(TypeError): pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
self.__dict__[name] = value
else:
raise self.DeclarationError("Variable '%s' not declared" % name)
self.__dict__[name]=value
def declare(self, **args):
for name, value in args.items():
self.__dict__[name] = value
sys.modules[__name__]=_variable()
It took me less than five minutes starting from Alex Martelli's code here
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207
No special syntax or macros or magic powers were needed. I could extend
the variables functionality to (say) make sure the same variable isn't
declared twice, or be case-insensitive, or have multiple namespaces, none
of which need special syntax.
--
Steven.
More information about the Python-list
mailing list