Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 38 additions & 69 deletions src/idl_gen_python.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ class PythonStubGenerator {
public:
PythonStubGenerator(const Parser &parser, const std::string &path,
const Version &version)
: parser_{parser},
namer_{WithFlagOptions(kStubConfig, parser.opts, path),
Keywords(version)},
: parser_{ parser },
namer_{ WithFlagOptions(kStubConfig, parser.opts, path),
Keywords(version) },
version_(version) {}

bool Generate() {
Expand Down Expand Up @@ -140,8 +140,7 @@ class PythonStubGenerator {
return module;
}

template <typename T>
std::string ModuleFor(const T *def) const {
template<typename T> std::string ModuleFor(const T *def) const {
if (parser_.opts.one_file) return ModuleForFile(def->file);
return namer_.NamespacedType(*def);
}
Expand All @@ -165,7 +164,7 @@ class PythonStubGenerator {
return "None";
}

template <typename F>
template<typename F>
std::string UnionType(const EnumDef &enum_def, Imports *imports,
F type) const {
imports->Import("typing");
Expand All @@ -181,14 +180,9 @@ class PythonStubGenerator {
result += import.name;
break;
}
case BASE_TYPE_STRING:
result += "str";
break;
case BASE_TYPE_NONE:
result += "None";
break;
default:
break;
case BASE_TYPE_STRING: result += "str"; break;
case BASE_TYPE_NONE: result += "None"; break;
default: break;
}
}
return "typing.Union[" + result + "]";
Expand All @@ -208,13 +202,11 @@ class PythonStubGenerator {

std::string EnumType(const EnumDef &enum_def, Imports *imports) const {
imports->Import("typing");
const Import &import =
imports->Import(ModuleFor(&enum_def), namer_.Type(enum_def));

std::string result = "";
for (const EnumVal *val : enum_def.Vals()) {
if (!result.empty()) result += ", ";
result += import.name + "." + namer_.Variant(*val);
result += namer_.Type(enum_def) + "." + namer_.Variant(*val);
}
return "typing.Literal[" + result + "]";
}
Expand All @@ -229,18 +221,14 @@ class PythonStubGenerator {
namer_.Type(*type.struct_def));
return import.name;
}
case BASE_TYPE_STRING:
return "str";
case BASE_TYPE_STRING: return "str";
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: {
imports->Import("typing");
return "typing.List[" + TypeOf(type.VectorType(), imports) + "]";
}
case BASE_TYPE_UNION:
return UnionType(*type.enum_def, imports);
default:
FLATBUFFERS_ASSERT(0);
return "";
case BASE_TYPE_UNION: return UnionType(*type.enum_def, imports);
default: FLATBUFFERS_ASSERT(0); return "";
}
}

Expand All @@ -262,8 +250,7 @@ class PythonStubGenerator {
namer_.ObjectType(*field_type.struct_def));
return field_name + ": " + import.name + " | None";
}
case BASE_TYPE_STRING:
return field_name + ": str | None";
case BASE_TYPE_STRING: return field_name + ": str | None";
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: {
imports->Import("typing");
Expand All @@ -282,8 +269,7 @@ class PythonStubGenerator {
case BASE_TYPE_UNION:
return field_name + ": " +
UnionObjectType(*field->value.type.enum_def, imports);
default:
return field_name;
default: return field_name;
}
}

Expand All @@ -307,15 +293,12 @@ class PythonStubGenerator {
stub << " def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> " << name
<< ": ...\n";

const Import &import =
imports->Import(ModuleFor(struct_def), namer_.Type(*struct_def));

stub << " @classmethod\n";
stub << " def InitFromObj(cls, " << namer_.Variable(*struct_def)
<< ": " + import.name + ") -> " << name << ": ...\n";
<< ": " + namer_.Type(*struct_def) + ") -> " << name << ": ...\n";

stub << " def _UnPack(self, " << namer_.Variable(*struct_def) << ": "
<< import.name << ") -> None: ...\n";
<< namer_.Type(*struct_def) << ") -> None: ...\n";

stub << " def Pack(self, builder: flatbuffers.Builder) -> None: ...\n";

Expand Down Expand Up @@ -424,8 +407,7 @@ class PythonStubGenerator {
stub << " def " << name << "(self) -> table.Table | None: ...\n";
break;
}
default:
break;
default: break;
}
}
}
Expand Down Expand Up @@ -469,9 +451,7 @@ class PythonStubGenerator {
stub << '\n';
stub << "def Create" + namer_.Type(*struct_def)
<< "(builder: flatbuffers.Builder";
for (const std::string &arg : args) {
stub << ", " << arg;
}
for (const std::string &arg : args) { stub << ", " << arg; }
stub << ") -> uoffset: ...\n";
}

Expand Down Expand Up @@ -546,11 +526,10 @@ class PythonStubGenerator {
Imports *imports) const {
stub << "class " << namer_.Type(*enum_def);

if (version_.major == 3){
if (version_.major == 3) {
imports->Import("enum", "IntEnum");
stub << "(IntEnum)";
}
else {
} else {
stub << "(object)";
}

Expand All @@ -573,9 +552,7 @@ class PythonStubGenerator {
ss << "from __future__ import annotations\n";
ss << '\n';
ss << "import flatbuffers\n";
if (parser_.opts.python_gen_numpy) {
ss << "import numpy as np\n";
}
if (parser_.opts.python_gen_numpy) { ss << "import numpy as np\n"; }
ss << '\n';

std::set<std::string> modules;
Expand Down Expand Up @@ -607,7 +584,8 @@ class PythonStubGenerator {
const Parser &parser_;
const IdlNamer namer_;
const Version version_;
};} // namespace
};
} // namespace

class PythonGenerator : public BaseGenerator {
public:
Expand All @@ -616,8 +594,8 @@ class PythonGenerator : public BaseGenerator {
: BaseGenerator(parser, path, file_name, "" /* not used */,
"" /* not used */, "py"),
float_const_gen_("float('nan')", "float('inf')", "float('-inf')"),
namer_(WithFlagOptions(kConfig, parser.opts, path),
Keywords(version)) {}
namer_(WithFlagOptions(kConfig, parser.opts, path), Keywords(version)) {
}

// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
Expand Down Expand Up @@ -807,9 +785,8 @@ class PythonGenerator : public BaseGenerator {
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);

const ImportMapEntry import_entry = {
GenPackageReference(field.value.type), TypeName(field)
};
const ImportMapEntry import_entry = { GenPackageReference(field.value.type),
TypeName(field) };

if (parser_.opts.python_typing) {
const std::string return_type = ReturnType(struct_def, field);
Expand Down Expand Up @@ -869,9 +846,8 @@ class PythonGenerator : public BaseGenerator {
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "(self)";

const ImportMapEntry import_entry = {
GenPackageReference(field.value.type), TypeName(field)
};
const ImportMapEntry import_entry = { GenPackageReference(field.value.type),
TypeName(field) };

if (parser_.opts.python_typing) {
const std::string return_type = ReturnType(struct_def, field);
Expand Down Expand Up @@ -957,11 +933,8 @@ class PythonGenerator : public BaseGenerator {
code += Indent + Indent + "return None\n\n";
}

template <typename T>
std::string ModuleFor(const T *def) const {
if (!parser_.opts.one_file) {
return namer_.NamespacedType(*def);
}
template<typename T> std::string ModuleFor(const T *def) const {
if (!parser_.opts.one_file) { return namer_.NamespacedType(*def); }

std::string filename =
StripExtension(def->file) + parser_.opts.filename_suffix;
Expand Down Expand Up @@ -991,9 +964,8 @@ class PythonGenerator : public BaseGenerator {

GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
const ImportMapEntry import_entry = {
GenPackageReference(field.value.type), TypeName(field)
};
const ImportMapEntry import_entry = { GenPackageReference(field.value.type),
TypeName(field) };

if (parser_.opts.python_typing) {
const std::string return_type = ReturnType(struct_def, field);
Expand Down Expand Up @@ -1116,8 +1088,7 @@ class PythonGenerator : public BaseGenerator {
std::string qualified_name = NestedFlatbufferType(unqualified_name);
if (qualified_name.empty()) { qualified_name = nested->constant; }

const ImportMapEntry import_entry = { qualified_name,
unqualified_name };
const ImportMapEntry import_entry = { qualified_name, unqualified_name };

auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
Expand Down Expand Up @@ -2226,9 +2197,9 @@ class PythonGenerator : public BaseGenerator {

if (parser_.opts.python_gen_numpy) {
code_prefix += GenIndents(3) + "if np is not None and type(self." +
field_field + ") is np.ndarray:";
field_field + ") is np.ndarray:";
code_prefix += GenIndents(4) + field_field +
" = builder.CreateNumpyVector(self." + field_field + ")";
" = builder.CreateNumpyVector(self." + field_field + ")";
code_prefix += GenIndents(3) + "else:";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4);
code_prefix += "(self." + field_field + "[i])";
Expand Down Expand Up @@ -2676,9 +2647,7 @@ class PythonGenerator : public BaseGenerator {
}
}
}
if (parser_.opts.python_gen_numpy) {
code += "np = import_numpy()\n\n";
}
if (parser_.opts.python_gen_numpy) { code += "np = import_numpy()\n\n"; }
}
}

Expand Down Expand Up @@ -2719,7 +2688,7 @@ class PythonGenerator : public BaseGenerator {

static bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name) {
python::Version version{parser.opts.python_version};
python::Version version{ parser.opts.python_version };
if (!version.IsValid()) return false;

python::PythonGenerator generator(parser, path, file_name, version);
Expand Down
2 changes: 0 additions & 2 deletions tests/MyGame/Example/ArrayStruct.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.ArrayStruct import ArrayStruct
from MyGame.Example.NestedStruct import NestedStruct, NestedStructT
from MyGame.Example.TestEnum import TestEnum

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down
1 change: 0 additions & 1 deletion tests/MyGame/Example/ArrayTable.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import numpy as np
import flatbuffers
import typing
from MyGame.Example.ArrayStruct import ArrayStruct, ArrayStructT
from MyGame.Example.ArrayTable import ArrayTable

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down
2 changes: 0 additions & 2 deletions tests/MyGame/Example/NestedStruct.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.NestedStruct import NestedStruct
from MyGame.Example.TestEnum import TestEnum

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down
1 change: 0 additions & 1 deletion tests/MyGame/Example/NestedUnion/Any.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.NestedUnion.Any import Any
from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnum
from MyGame.Example.NestedUnion.Vec3 import Vec3
from flatbuffers import table
Expand Down
2 changes: 0 additions & 2 deletions tests/MyGame/Example/NestedUnion/NestedUnionTest.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.NestedUnion.Any import Any
from MyGame.Example.NestedUnion.NestedUnionTest import NestedUnionTest
from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnumT
from MyGame.Example.NestedUnion.Vec3 import Vec3T
from flatbuffers import table
Expand Down
1 change: 0 additions & 1 deletion tests/MyGame/Example/NestedUnion/Test.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.NestedUnion.Test import Test

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.NestedUnion.Color import Color
from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnum

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down
2 changes: 0 additions & 2 deletions tests/MyGame/Example/NestedUnion/Vec3.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import numpy as np

import flatbuffers
import typing
from MyGame.Example.NestedUnion.Color import Color
from MyGame.Example.NestedUnion.Test import Test, TestT
from MyGame.Example.NestedUnion.Vec3 import Vec3

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down
1 change: 0 additions & 1 deletion tests/MyGame/MonsterExtra.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import numpy as np

import flatbuffers
import typing
from MyGame.MonsterExtra import MonsterExtra

uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type

Expand Down