if instance exists problem ..

Paul Hankin paul.hankin at gmail.com
Wed Oct 17 19:12:15 EDT 2007


On Oct 17, 11:39 pm, stef mientki <stef.mien... at gmail.com> wrote:
> the test if an instance exists, always returns false.
>     ini = inifile (filename)
>     if ini:
>         print 'ok',type(ini)
>     else:
>         print 'wrong',type(ini)
>
> Why is that ?
> What should I do to the same simple test for existance ?

First, object construction always gives you an object or raises an
exception, so you don't have to test for existence. If you don't know
if an object has been created, you should initialise ini to None, and
test with 'if ini is not None:'.

'if x' doesn't test if x exists, it tests if x when cast to a bool is
True. ConfigParser acts like a container, and returns False if it's
empty. Your class is (indirectly) a subclass of ConfigParser, but is
never initialised as such, and so is empty. So 'if ini' returns False,
and you get your confused result.

You need to decide if inifile is a subclass of ConfigObj, or is a
wrapper round a ConfigObj. Probably you want the former and your init
method should be something like:
  def __init__(self, filename):
    ConfigObj.__init__(self, filename, list_values=False,
      write_empty_values=True)
    self.newlines = '\r\n'
    self.Section = ''
    self.Modified = False

--
Paul Hankin




More information about the Python-list mailing list