@defpython directive

Informally the @defpython directive is of the form


@defpython macroname(a1,...,an) = y

It defines a macro (in a similar fashion to the @def directive). The substitution string is macro expanded then executed as a python expression that must evaluate to an int, float or string. The @defpython directive itself is stripped from the generated output. i.e. it macro expands into nothing.

The following example assumes the @runpython example has already been executed in order to define the getfibnumbers function in the Python interpreter:

Before translationAfter translation
@defpython getfib(int x) =
{
    # This is python!
    # A python expression that
    # evaluates to a string
    str(getfibnumbers(x))
}
const char* f()
{
    return @str(getfib(6));
}








const char* f()
{
    return "[1, 1, 2, 3, 5]";
}

Practical examples using Python

Python provides very convenient string handling functions that can readily be made available as macros. For example:


@defpython int mStringLength(s) =
{
    len(@str(s))
}
@defpython mGetSubString(s,int i1,int i2) =
{
    (@str(s))[i1:i2]
}
@defpython mGetCharInString(s,int i) =
{
    (@str(s))[i]
}
@defpython mToUpper(s) =
{
    @str(s).upper()
}
@defpython mToLower(s) =
{
    @str(s).lower()
}
@defpython mCapitaliseFirstLetter(s) =
{
    @str(s).capitalize()
}
@defpython mEatLeadingWhitespace(s) =
{
    @str(s).lstrip()
}
@defpython mEatTrailingWhitespace(s) =
{
    @str(s).rstrip()
}
@defpython string mCentreJustify(s,int width) =
{
    @str(s).center(width)
}
@defpython mLeftJustify(s,int width) =
{
    @str(s).ljust(width)
}
@defpython mRightJustify(s,int width) =
{
    @str(s).rjust(width)
}

Which for example allows:

Before translationAfter translation
const char* f()
{
    return @str(mCentreJustify(mToUpper(hello),11));
}

const char* f()
{
    return "   HELLO   ";
}