[Python] Generate .pyi stub files when --python-typing is on. (#8312)

* [Python] Generate `.pyi` stub files when `--python-typing` is on.

To support this change, the following modifications were made:

-  added a new option to disable `numpy` helpers generation;
-  added a new flag to control the target Python version:

   `--python-version` can be one of the following:

   - `0.x.x` – compatible with any Python version;
   - `2.x.x` – compatible with Python 2;
   - `3.x.x` – compatible with Python 3.
-  added codegen utilities for Python;
-  added a note that the generated .py file is empty.

* [Python] Update Bazel build rules.

* [Python] Update Bazel build rules.

* [Python] Run buildifier on BUILD.bazel files.

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
This commit is contained in:
Anton Bobukh
2024-05-29 12:47:29 -07:00
committed by GitHub
parent 58c8eb5847
commit 3b27f5396e
27 changed files with 2865 additions and 34 deletions

63
include/codegen/python.cc Normal file
View File

@@ -0,0 +1,63 @@
#include "codegen/python.h"
#include <set>
#include <sstream>
#include <string>
#include <utility>
namespace flatbuffers {
namespace python {
Version::Version(const std::string &version) {
std::stringstream ss(version);
char dot;
ss >> major >> dot >> minor >> dot >> micro;
}
bool Version::IsValid() const {
return (major == 0 || major == 2 || major == 3) && minor >= 0 && micro >= 0;
}
std::set<std::string> Keywords(const Version &version) {
switch (version.major) {
case 2:
// https://docs.python.org/2/reference/lexical_analysis.html#keywords
return {
"and", "as", "assert", "break", "class", "continue", "def",
"del", "elif", "else", "except", "exec", "finally", "for",
"from", "global", "if", "import", "in", "is", "lambda",
"not", "or", "pass", "print", "raise", "return", "try",
"while", "with", "yield",
};
case 0:
case 3:
// https://docs.python.org/3/reference/lexical_analysis.html#keywords
return {
"and", "as", "assert", "async", "await", "break",
"class", "continue", "def", "del", "elif", "else",
"except", "False", "finally", "for", "from", "global",
"if", "import", "in", "is", "lambda", "None",
"nonlocal", "not", "or", "pass", "raise", "return",
"True", "try", "while", "with", "yield",
};
default:
return {};
}
}
const python::Import &python::Imports::Import(const std::string &module) {
python::Import import;
import.module = module;
imports.push_back(std::move(import));
return imports.back();
}
const python::Import &python::Imports::Import(const std::string &module,
const std::string &name) {
python::Import import;
import.module = module;
import.name = name;
imports.push_back(std::move(import));
return imports.back();
}
} // namespace python
} // namespace flatbuffers