stackoverflow question

Terry Reedy tjreedy at udel.edu
Sat Mar 10 13:00:03 EST 2012


On 3/10/2012 11:56 AM, Ethan Furman wrote:

>>> I'm writing a metaclass to do some cool stuff, and part of its
>>> processing is to check that certain attributes exist when the class is
>>> created. Some of these are mutable, and would normally be set in
>>> `__init__`, but since `__init__` isn't run until the instance is created
>>> the metaclass won't know that the attribute *will* be created, and
>>> raises an error.

>> c. Check the code object to see if the attribute will be created.
>
> I have no idea how to do this -- pointers?

Capture output of dis.dis(targetclass.__init__) by temporarily setting 
sys.stdout to StringIO object. (There is tracker issue to make lines 
available to a program without doing this.)

 >>> from dis import dis
 >>> def f(self):
	self.attr = 1
	
 >>> dis(f)
   2           0 LOAD_CONST               1 (1)
               3 LOAD_FAST                0 (self)
               6 STORE_ATTR               0 (attr)
               9 LOAD_CONST               0 (None)
              12 RETURN_VALUE

Look for STORE_ATTR line with target attribute name. If you want to 
check for wacko code that does setattr(self, 'attr', value), try it in 
'f' and dis again.

Anything to do with code objects (and dis module) is implementation and 
version specific

---
Terry Jan Reedy



More information about the Python-list mailing list