1

I am trying to make it so that when i am setting a variable, I get a compile-type error when I misspell it. in all my attempts so far, the variable just gets created.

I don't mind to put the variables in a class, a module, a dictionary or any combination. I just want to have a compile time error on misspeling

here is an example:

class Foo:
   bar=""
   def __init__(self,bar_value):
     self.barr=bar_value # want syntax error here
the_foo=Foo("hellow")

edit: I had my terminology wrong: I meant static typing

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
yigal
  • 3,923
  • 8
  • 37
  • 59

3 Answers3

2

What you're looking for is static code analysis. In this case you should look at something like PyLint

See this question for further discussion.

Note: Python is strongly typed already, causing the confusion.

Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
2

Note that Python is stroingly typed see this question for why. What you are after is part of static code analysis.

Some IDEs do check that variable names have been set see PyDev under Eclipse and PyCharm, and using an IDE is I expect the only waty to get these errors spotted whilst typing.

Code analysers like PyLint can be run on the code and these spot some errors.

Community
  • 1
  • 1
mmmmmm
  • 32,227
  • 27
  • 88
  • 117
2

Python is strongly typed - the closest you could get using a class is to restrict attribute creation using __slots__ eg:

class Foo(object):
    __slots__ = ['bar']
    def __init__(self, bar_value):
        self.barr = bar_value

the_foo = Foo('bar value')
# AttributeError: 'Foo' object has no attribute 'barr'

More info about slots in the Python Data model

TL;DR: This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. If defined in a new-style class, __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • I just tried that, but i don't seems to get my error yet. I am using python 2.7. What are those "new style classes" and how do i make one? – yigal Dec 02 '13 at 16:12
  • 1
    @Yigal did you copy/paste the above exactly? New style classes in 2.x inherit from `object`... hence the `class Foo(object)` instead of `class Foo`... – Jon Clements Dec 02 '13 at 16:14
  • yes, i missed that (object), now i get the error message, nice! – yigal Dec 02 '13 at 16:16
  • I will. it seems like a very nifty construct. Thanks for bringing it to my attention! – yigal Dec 02 '13 at 16:40