Python Newbie

Roy Smith roy at panix.com
Sun Feb 24 19:42:21 EST 2013


In article <mailman.2461.1361749985.2939.python-list at python.org>,
 Ethan Furman <ethan at stoneleaf.us> wrote:

> On 02/24/2013 03:38 PM, piterrr.dolinski at gmail.com wrote:
> >
> >>> intX = 32                          # decl + init int var
> >> How is it not obvious that "intX" is an integer *without* the comment?
> >
> > Indeed the assignment is enough to deduce "intX" is an int. The comment is 
> > there to let me know it is unlikely intX appears earlier in the code. 
> > Please, let me do things my way until I find reasons to the contrary.
> 
> Of course you can, but wouldn't you rather find reasons to the contrary by us 
> telling you, instead of tripping
> over something yourself?
> 
> For example (I believe it's already been mentioned) "declaring" intX with 
> some integer value does *nothing* to maintain 
> X as an integer:
> 
> --> intX = 32
> --> intX = intX / 3.0
> --> intX
> 10.6666666666

I could imagine a getattr-based implementation of DBC (Design By 
Contract) which does use the variable name to enforce type.  Unclear if 
this is a Good Thing, a Bad Thing, or a just plain Crazy Thing.  In any 
cae, it would be a neat (if somewhat advanced) exercise for somebody 
interested in enforcing types and looking to explore some of the more 
arcane corners of Python.

class DBC_Example:
   # Ad-libbing this, code not tested
   def __setattr__(self, name, value):
      if name.startswith('int'):
         assert isinstance(value, int)
      self.__dict__[name] = value



More information about the Python-list mailing list