by BenFrantzDale · 5y ago · 0 comments
However, enum is also a heavy-duty solution. It requires slightly more typing, but more importantly, it requires exporting an enum to all call-sites. Both in C++ and in python this is not desirable.
I'd say the enum should be in the toolbox, especially if the flag is important to the business logic of the code, and is likely to thread throughout it. But for quick work, a key-word only argument can work just as well. Especially if the flag is never to be passed on.
calc(x, y, mode="gain")
where the function is defined as def calc(
x: float,
y: float,
*,
mode: Literal["gain", "render"],
) -> float:
...
This is IMO one of the best things type annotations provide. Combined with Protocol you can write much better structured code with little or no runtime costs.Given the reasonable namespacing that C++ and python [modules] provide, and that you have to export the complete calling specification of the function to the caller anyway (whether it's an enum, a positional boolean or a keyword argument), what's the drawback of the enum option?
If you use namespaced imports then the call is going to become very long by having the package name included twice.
In C++ you are dealing with needing to drop the enum in a header file, requiring a two file change and making headers bigger. The call-side has the same potential namespace problem, but less badly.
enum gain_type { enable_gain, disable_gain };