Welcome, guest | Sign In | My Account | Store | Cart

Script that raises an error when you didn't declare a property in the __init__ method.

Python, 66 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Here's something I found useful when developing python programs. It takes advantage of
my convention to initialize properties that I want to use in the constructor.
This script checks this initialization and complains when a variable wasn't defined.

Great for detecting typos early - what I like most is that when you are ready developing
your script, you just throw the whole thing away from your source and you have no
performance penalty.

It heavily depends on the articles of Alex Martinelli: 'Constants in Python' and 
'Determining Current Function Name' here at ASPN. You could beef this up with
typechecking (see the comments of Philip Nunez at Alex' 'Constants...' article).

Dirk Krause, d_krause@pixelpark.com, 11/08/2001
"""



import sys

def caller():
    try:
        raise RuntimeError
    except RuntimeError:
        exc, val, tb = sys.exc_info()
        frame = tb.tb_frame.f_back
        del exc, val, tb
    try:
        return frame.f_back.f_code.co_name
    except AttributeError:  # called from the top
        return None


class ObjectWithCheck:

    def __setattr__(self, name, value):
    
        c = caller()
        if c == '__init__' or hasattr(self, name):
            self.__dict__[name] = value
        else:
            raise TypeError, self.__class__.__name__ + 'error: variable was not declared!'



class myObjWithCheck(ObjectWithCheck):
    def __init__(self):
        self.somevariable = 0


class myObjWithoutCheck:
    def __init__(self):
        self.somevariable = 0


o = myObjWithoutCheck()

o.somevariable = 2
o.somevaiable = 2   #  This line seems ok ...



o = myObjWithCheck()

o.somevariable = 2
o.somevaiable = 2   #  ... this line raises an error!

Here's something I found useful when developing python programs. It takes advantage of my convention to initialize properties that I want to use in the constructor. This script checks this initialization and complains when a variable wasn't defined.

Great for detecting typos early - what I like most is that when you are ready developing your script, you just throw the whole thing away from your source and you have no performance penalty.

It heavily depends on the articles of Alex Martinelli: 'Constants in Python' and 'Determining Current Function Name' here at ASPN. You could beef this up with typechecking (see the comments of Philip Nunez at Alex' 'Constants...' article).

Dirk Krause, d_krause@pixelpark.com, 11/08/2001

Created by Dirk Krause on Thu, 8 Nov 2001 (PSF)
Python recipes (4591)
Dirk Krause's recipes (2)

Required Modules

Other Information and Tasks