[cfe-commits] [PATCH 4/4] [clang.py] TranslationUnit API improvements

Anders Waldenborg anders at 0x63.nu
Mon May 14 12:23:30 PDT 2012


On Sat, May 12, 2012 at 02:19:08PM -0700, Gregory Szorc wrote:
> On Mon, May 7, 2012 at 11:17 PM, Anders Waldenborg <anders at 0x63.nu> wrote:
> > Also possibly mention the -x argument in the paragraph
> > about "C++ in test.c".
> 
> What are you referring to?

I'm was referring last paragraph in TranslationUnit.from_source
documentation:

  Also note that Clang infers the source language from the extension of   
  the input filename. If you pass in source code containing a C++ class   
  declaration with the filename "test.c" parsing will fail.

I was thinking that it would be useful to mention "-x" in that
context. eg:
TranslationUnit.from_source(args=["-x", "c", "filewithnonstandardextension.code"])

[...]

> > Did you consider to make the different types of
> > TranslationUnitSaveError subclasses?
> 
> Yes, and it didn't feel very Pythonic. If I were writing Java, this is
> probably how I would do it. But, Python is not Java. If there is more
> data hung off save errors later, then we have a case for different
> classes. Until then, I think simplicity should win.

<Bikeshedding begins - feel free to ignore>

I'm not sure I agree about which is most pythonic of those variants.
I'm not dutch but I would say the most pythonic way would be to use
built-in exceptions to greatest possible extent (so in this case if
res == 1: raise RuntimeError("Known unknown error saving tu") elif res
== 2: raise ValueError("Error saving tu with errors") elif res == 3:
raise TypeError("Not a valid tu")).

My point was not to make a javaish huge class hierachy just because.
But as the only attribute on the exception was a sub-type it felt
natural to instead expose this in the type.

TranslationUnitSaveError(Exception):
    pass
TranslationUnitUnknownError(TranslationUnitSaveError):
    pass
TranslationUnitSaveWithErrorsError(TranslationUnitSaveError):
    pass
TranslationUnitInvalidError(TranslationUnitSaveError):
    pass

This gives effortless string representation (as the class name is
included):

>>> tu.save()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in save
TranslationUnitSaveWithErrorsError: Couldn't save translationunit

Also I find it annoying to have to inspect attributes of the exception
to know how to handle it. Like this:

  try:
      op()
  except IOError as e:
      if e.errno in nonfatalerrnos:
          continue
      raise

This became way too long for such tiny detail. I guess I just had to
defend myself after being accused for writing java in python :)

 anders



More information about the cfe-commits mailing list