Search code examples
pythonffi

python: class instance can't see self attribute


In my project i use module from known bt_manager to decode sbc audio stream. This module is python wrap for C-functions from rtpsbc library.

class SBCCodec:
    def __init__(self, config):

            import sys

            try:
                self.codec = ffi.verify(b'#include "rtpsbc.h"',
                                        libraries=[b'rtpsbc'],
                                        ext_package=b'rtpsbc')
            except:
                print 'Exception:', sys.exc_info()[0]

            self.config = ffi.new('sbc_t *')
            self.ts = ffi.new('unsigned int *', 0)
            self.seq_num = ffi.new('unsigned int *', 0)
            self._init_sbc_config(config)
            self.codec.sbc_init(self.config, 0)

When i try to create SBCCodec class instance it gives me:

AttributeError: SBCCodec instance has no attribute 'codec'

You can see this attribute in the piece of code i posted above. It works with ffi-methods (ffi.verify, ffi.new). When i input those commands in ipython everything works correct without errors.

What have i missed?


Solution

  • As @Torxed has already mentioned the only way this would happen is if ffi.verify inside your try block throws an exception. If that happens self.codec will not be initialised. If that happens your code does not rethrow the exception and continues as normal after simply printing (which is not clean behaviour). The final statement then tries to call self.codec.config.sbc_init, that is it assumes that self.codec is already intialised, which is incorrect in this particular case and that is why you get the AttibuteError.

    If you want to create the instance anyway regardless of the failure for ffi.verify at the start of init define self.codec = None and in your final statement insert a check such as:

    if (self.codec != None ):
       self.codec.sbc_init(self.config, 0)
    

    Hope that helps.