diff --git a/include/codegen/python.h b/include/codegen/python.h index cc6c241f2d6..3afb229d287 100644 --- a/include/codegen/python.h +++ b/include/codegen/python.h @@ -74,7 +74,7 @@ struct Version { std::set Keywords(const Version& version); struct Import { - bool IsLocal() const { return module == "."; } + bool IsLocal() const; std::string module; std::string name; diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp index 4c48b21b17d..fecdd1227e7 100644 --- a/src/idl_gen_python.cpp +++ b/src/idl_gen_python.cpp @@ -32,7 +32,6 @@ #include "codegen/idl_namer.h" #include "codegen/python.h" #include "flatbuffers/code_generators.h" -#include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" @@ -41,13 +40,85 @@ namespace python { namespace { -typedef std::pair ImportMapEntry; -typedef std::set ImportMap; - // Hardcode spaces per indentation. static const CommentConfig def_comment = {nullptr, "#", nullptr}; static const std::string Indent = " "; +class ImportMap { + public: + using Mod = std::string; + using Type = std::string; + using MapType = std::map>; + + using iterator = MapType::iterator; + using const_iterator = MapType::const_iterator; + + ImportMap() = default; + + iterator begin() { return imports_.begin(); } + const_iterator begin() const { return imports_.begin(); } + const_iterator cbegin() const { return imports_.cbegin(); } + + iterator end() { return imports_.end(); } + const_iterator end() const { return imports_.end(); } + const_iterator cend() const { return imports_.cend(); } + + // Add an import to the map + void Add(const std::string& mod, std::string type) { + if (type.empty()) { + // If the type is empty, we only add the module + imports_[mod]; + } else { + imports_[mod].emplace(std::move(type)); + } + } + + // Add an import to the map + void Add(const Import& import) { Add(import.module, import.name); } + + // Check whether the map contains a given module and type + bool Contains(const std::string& mod, const std::string& type) const { + auto it = imports_.find(mod); + if (it == imports_.end()) return false; + const auto& types = it->second; + return types.find(type) != types.end(); + } + + // Check whether the map contains a given import + bool Contains(const Import& import) const { + return Contains(import.module, import.name); + } + + // Merges another ImportMap into this one. + void Merge(const ImportMap& other) { + for (const auto& entry : other.imports_) { + auto& types = entry.second; + imports_[entry.first].insert(types.begin(), types.end()); + } + } + + // Checks whether the map is empty. + bool Empty() const { return imports_.empty(); } + + private: + MapType imports_; +}; + +bool StartsWith(const std::string& str, char c) { + return !str.empty() && str.front() == c; +} + +// Starts a new line and then indents. +std::string GenIndents(std::size_t num) { + return "\n" + std::string(num * Indent.length(), ' '); +} + +std::string GenImportStatement(std::size_t indent, const Import& import) { + if (import.IsLocal()) return {}; + return GenIndents(indent) + "from " + import.module + " import " + + import.name; +} + class PythonStubGenerator { public: PythonStubGenerator(const Parser& parser, const std::string& path, @@ -689,8 +760,11 @@ class PythonStubGenerator { const IdlNamer namer_; const Version version_; }; + } // namespace +bool Import::IsLocal() const { return StartsWith(module, '.'); } + class PythonGenerator : public BaseGenerator { public: PythonGenerator(const Parser& parser, const std::string& path, @@ -724,11 +798,6 @@ class PythonGenerator : public BaseGenerator { code += "class " + namer_.Type(enum_def) + "(object):\n"; } - // Starts a new line and then indents. - std::string GenIndents(int num) const { - return "\n" + std::string(num * Indent.length(), ' '); - } - // A single enum member. void EnumMember(const EnumDef& enum_def, const EnumVal& ev, std::string* code_ptr) const { @@ -892,30 +961,21 @@ class PythonGenerator : public BaseGenerator { std::string* code_ptr, ImportMap& imports) const { auto& code = *code_ptr; const auto vec_type = field.value.type.VectorType(); + const auto import = Field2Import(field); + GenReceiver(struct_def, code_ptr); code += namer_.Method(field); - const ImportMapEntry import_entry = {GenPackageReference(field.value.type), - TypeName(field)}; - if (parser_.opts.python_typing) { + imports.Add(import); const std::string return_type = ReturnType(struct_def, field); - code += "(self, i: int)"; - code += " -> " + return_type + ":"; - - imports.insert(import_entry); + code += "(self, i: int) -> " + return_type + ":"; } else { code += "(self, i):"; + code += GenImportStatement(2, import); } - if (parser_.opts.include_dependence_headers && - !parser_.opts.python_typing) { - code += GenIndents(2); - code += "from " + import_entry.first + " import " + import_entry.second + - "\n"; - } - - code += GenIndents(2) + "obj = " + TypeName(field) + "()"; + code += GenIndents(2) + "obj = " + import.name + "()"; code += GenIndents(2) + "obj.Init(self._tab.Bytes, self._tab.Pos + "; code += NumToString(field.value.offset) + " + i * "; code += NumToString(InlineSize(vec_type)); @@ -953,37 +1013,32 @@ class PythonGenerator : public BaseGenerator { void GetStructFieldOfTable(const StructDef& struct_def, const FieldDef& field, std::string* code_ptr, ImportMap& imports) const { auto& code = *code_ptr; + const auto import = Field2Import(field); + GenReceiver(struct_def, code_ptr); code += namer_.Method(field) + "(self)"; - const ImportMapEntry import_entry = {GenPackageReference(field.value.type), - TypeName(field)}; - if (parser_.opts.python_typing) { + imports.Add(import); const std::string return_type = ReturnType(struct_def, field); code += " -> Optional[" + return_type + "]"; - imports.insert(ImportMapEntry{"typing", "Optional"}); - imports.insert(import_entry); + imports.Add("typing", "Optional"); } code += ":"; code += OffsetPrefix(field); + code += Indent + Indent + Indent; if (field.value.type.struct_def->fixed) { - code += Indent + Indent + Indent + "x = o + self._tab.Pos\n"; + code += "x = o + self._tab.Pos"; } else { - code += Indent + Indent + Indent; - code += "x = self._tab.Indirect(o + self._tab.Pos)\n"; + code += "x = self._tab.Indirect(o + self._tab.Pos)"; } - if (parser_.opts.include_dependence_headers && - !parser_.opts.python_typing) { - code += Indent + Indent + Indent; - code += "from " + import_entry.first + " import " + import_entry.second + - "\n"; - } - code += Indent + Indent + Indent + "obj = " + TypeName(field) + "()\n"; - code += Indent + Indent + Indent + "obj.Init(self._tab.Bytes, x)\n"; - code += Indent + Indent + Indent + "return obj\n"; - code += Indent + Indent + "return None\n\n"; + if (!imports.Contains(import)) code += GenImportStatement(3, import); + + code += GenIndents(3) + "obj = " + import.name + "()"; + code += GenIndents(3) + "obj.Init(self._tab.Bytes, x)"; + code += GenIndents(3) + "return obj"; + code += GenIndents(2) + "return None\n\n"; } // Get the value of a string. @@ -995,7 +1050,7 @@ class PythonGenerator : public BaseGenerator { if (parser_.opts.python_typing) { code += "(self) -> Optional[str]:"; - imports.insert(ImportMapEntry{"typing", "Optional"}); + imports.Add("typing", "Optional"); } else { code += "(self):"; } @@ -1014,50 +1069,42 @@ class PythonGenerator : public BaseGenerator { std::string return_ty = "flatbuffers.table.Table"; bool is_native_table = TypeName(field) == "*flatbuffers.Table"; - ImportMapEntry import_entry; if (is_native_table) { - import_entry = ImportMapEntry{"flatbuffers.table", "Table"}; + imports.Add("flatbuffers.table", "Table"); } else { return_ty = TypeName(field); - import_entry = ImportMapEntry{GenPackageReference(field.value.type), - TypeName(field)}; + imports.Add(GenPackageReference(field.value.type), TypeName(field)); } code += namer_.Method(field) + "(self)"; if (parser_.opts.python_typing) { code += " -> Optional[" + return_ty + "]"; - imports.insert(ImportMapEntry{"typing", "Optional"}); - imports.insert(import_entry); + imports.Add("typing", "Optional"); } code += ":"; code += OffsetPrefix(field); - if (!parser_.opts.python_typing) { - code += Indent + Indent + Indent; - code += "from " + import_entry.first + " import " + import_entry.second + - "\n"; - } code += Indent + Indent + Indent + "obj = Table(bytearray(), 0)\n"; code += Indent + Indent + Indent + GenGetter(field.value.type); code += "obj, o)\n" + Indent + Indent + Indent + "return obj\n"; code += Indent + Indent + "return None\n\n"; } - template - std::string ModuleFor(const T* def) const { - if (!parser_.opts.one_file) { - return namer_.NamespacedType(*def); - } + std::string ModuleFor(const Definition* def) const { + if (!parser_.opts.one_file) return namer_.NamespacedType(*def); + + std::string def_file{def->file}; + if (def->declaration_file) def_file = def->declaration_file->substr(2); std::string filename = - StripExtension(def->file) + parser_.opts.filename_suffix; - if (parser_.file_being_parsed_ == def->file) { - return "." + StripPath(filename); // make it a "local" import - } + StripExtension(def_file) + parser_.opts.filename_suffix; + filename = StripPath(filename); + // Detect whether it's defined in the same file as being parsed and make it + // a local import if so. + if (parser_.file_being_parsed_ == def->file) return "." + filename; - std::string module = parser_.opts.include_prefix + filename; - std::replace(module.begin(), module.end(), '/', '.'); - return module; + auto ns = namer_.Namespace(*def->defined_namespace); + return ns + "." + filename; } // Generate the package reference when importing a struct or enum from its @@ -1073,39 +1120,36 @@ class PythonGenerator : public BaseGenerator { const FieldDef& field, std::string* code_ptr, ImportMap& imports) const { auto& code = *code_ptr; - auto vectortype = field.value.type.VectorType(); + const auto vectortype = field.value.type.VectorType(); + const auto import = Field2Import(field); GenReceiver(struct_def, code_ptr); code += namer_.Method(field); - const ImportMapEntry import_entry = {GenPackageReference(field.value.type), - TypeName(field)}; if (parser_.opts.python_typing) { + imports.Add(import); const std::string return_type = ReturnType(struct_def, field); code += "(self, j: int) -> Optional[" + return_type + "]"; - imports.insert(ImportMapEntry{"typing", "Optional"}); - imports.insert(import_entry); + imports.Add("typing", "Optional"); } else { code += "(self, j)"; } code += ":" + OffsetPrefix(field); - code += Indent + Indent + Indent + "x = self._tab.Vector(o)\n"; - code += Indent + Indent + Indent; + code += Indent + Indent + Indent + "x = self._tab.Vector(o)"; + code += GenIndents(3); code += "x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * "; - code += NumToString(InlineSize(vectortype)) + "\n"; + code += NumToString(InlineSize(vectortype)); + if (!(vectortype.struct_def->fixed)) { - code += Indent + Indent + Indent + "x = self._tab.Indirect(x)\n"; + code += GenIndents(3) + "x = self._tab.Indirect(x)"; } - if (parser_.opts.include_dependence_headers && - !parser_.opts.python_typing) { - code += Indent + Indent + Indent; - code += "from " + import_entry.first + " import " + import_entry.second + - "\n"; - } - code += Indent + Indent + Indent + "obj = " + TypeName(field) + "()\n"; - code += Indent + Indent + Indent + "obj.Init(self._tab.Bytes, x)\n"; - code += Indent + Indent + Indent + "return obj\n"; - code += Indent + Indent + "return None\n\n"; + + if (!imports.Contains(import)) code += GenImportStatement(3, import); + + code += GenIndents(3) + "obj = " + import.name + "()"; + code += GenIndents(3) + "obj.Init(self._tab.Bytes, x)"; + code += GenIndents(3) + "return obj"; + code += GenIndents(2) + "return None\n\n"; } // Get the value of a vector's non-struct member. Uses a named return @@ -1181,15 +1225,14 @@ class PythonGenerator : public BaseGenerator { std::string NestedFlatbufferType(std::string unqualified_name) const { StructDef* nested_root = parser_.LookupStruct(unqualified_name); - std::string qualified_name; if (nested_root == nullptr) { - qualified_name = namer_.NamespacedType( + std::string qualified_name = namer_.NamespacedType( parser_.current_namespace_->components, unqualified_name); // Double check qualified name just to be sure it exists. nested_root = parser_.LookupStruct(qualified_name); } FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser. - return qualified_name; + return ModuleFor(nested_root); } // Returns a nested flatbuffer as itself. @@ -1197,39 +1240,30 @@ class PythonGenerator : public BaseGenerator { const FieldDef& field, std::string* code_ptr, ImportMap& imports) const { auto nested = field.attributes.Lookup("nested_flatbuffer"); - if (!nested) { - return; - } // There is no nested flatbuffer. + if (!nested) return; // There is no nested flatbuffer. - const std::string unqualified_name = nested->constant; - std::string qualified_name = NestedFlatbufferType(unqualified_name); - if (qualified_name.empty()) { - qualified_name = nested->constant; - } + const std::string type = nested->constant; + std::string module = NestedFlatbufferType(type); + if (module.empty()) module = nested->constant; - const ImportMapEntry import_entry = {qualified_name, unqualified_name}; + const Import import{std::move(module), std::move(type)}; auto& code = *code_ptr; GenReceiver(struct_def, code_ptr); code += namer_.Method(field) + "NestedRoot(self)"; if (parser_.opts.python_typing) { - code += " -> Union[" + unqualified_name + ", int]"; - imports.insert(ImportMapEntry{"typing", "Union"}); - imports.insert(import_entry); + imports.Add(import); + code += " -> Union[" + import.name + ", int]"; + imports.Add("typing", "Union"); } code += ":"; - code += OffsetPrefix(field); + code += OffsetPrefix(field, false); - if (!parser_.opts.python_typing) { - code += Indent + Indent + Indent; - code += "from " + import_entry.first + " import " + import_entry.second + - "\n"; - } - code += Indent + Indent + Indent + "return " + unqualified_name; - code += ".GetRootAs"; - code += "(self._tab.Bytes, self._tab.Vector(o))\n"; - code += Indent + Indent + "return 0\n"; + if (!imports.Contains(import)) code += GenImportStatement(3, import); + code += GenIndents(3) + "return " + import.name; + code += ".GetRootAs(self._tab.Bytes, self._tab.Vector(o))"; + code += GenIndents(2) + "return 0\n"; code += "\n"; } @@ -1299,9 +1333,10 @@ class PythonGenerator : public BaseGenerator { const auto& field_type = field.value.type; const auto& type = IsArray(field_type) ? field_type.VectorType() : field_type; - if (field.padding) - code += - indent + " builder.Pad(" + NumToString(field.padding) + ")\n"; + if (field.padding) { + code += indent + Indent + "builder.Pad(" + NumToString(field.padding) + + ")\n"; + } if (IsStruct(field_type)) { StructBuilderBody(*field_type.struct_def, (nameprefix + (namer_.Field(field) + "_")).c_str(), @@ -1309,7 +1344,7 @@ class PythonGenerator : public BaseGenerator { } else { const auto index_var = "_idx" + NumToString(index); if (IsArray(field_type)) { - code += indent + " for " + index_var + " in range("; + code += indent + Indent + "for " + index_var + " in range("; code += NumToString(field_type.fixed_length); code += " , 0, -1):\n"; in_array = true; @@ -1319,8 +1354,8 @@ class PythonGenerator : public BaseGenerator { (nameprefix + (namer_.Field(field) + "_")).c_str(), code_ptr, index + 1, in_array); } else { - code += IsArray(field_type) ? " " : ""; - code += indent + " builder.Prepend" + GenMethod(field) + "("; + code += IsArray(field_type) ? Indent : ""; + code += indent + Indent + "builder.Prepend" + GenMethod(field) + "("; code += nameprefix + namer_.Variable(field); size_t array_cnt = index + (IsArray(field_type) ? 1 : 0); for (size_t i = 0; in_array && i < array_cnt; i++) { @@ -1746,30 +1781,22 @@ class PythonGenerator : public BaseGenerator { } } - void GenUnionInit(const FieldDef& field, std::string* field_types_ptr, - std::set* import_list, - std::set* import_typing_list) const { + std::string GenUnionInit(const FieldDef& field, ImportMap& imports) const { // Gets all possible types in the union. - import_typing_list->insert("Union"); - auto& field_types = *field_types_ptr; - field_types = "Union["; + imports.Add("typing", "Union"); + + std::string output{"Union["}; + + const auto* enum_def = field.value.type.enum_def; + for (const auto* ev_ptr : enum_def->Vals()) { + const auto& ev = *ev_ptr; - std::string separator_string = ", "; - auto enum_def = field.value.type.enum_def; - for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end(); - ++it) { - auto& ev = **it; // Union only supports string and table. std::string field_type; switch (ev.union_type.base_type) { case BASE_TYPE_STRUCT: field_type = namer_.ObjectType(*ev.union_type.struct_def); - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(ev.union_type); - field_type = package_reference + "." + field_type; - import_list->insert("import " + package_reference); - } - field_type = "'" + field_type + "'"; + imports.Add(GenPackageReference(ev.union_type), field_type); break; case BASE_TYPE_STRING: field_type += "str"; @@ -1780,101 +1807,76 @@ class PythonGenerator : public BaseGenerator { default: break; } - field_types += field_type + separator_string; + output += field_type + ", "; } // Removes the last separator_string. - field_types.erase(field_types.length() - separator_string.size()); - field_types += "]"; - - // Gets the import lists for the union. - if (parser_.opts.include_dependence_headers) { - const auto package_reference = GenPackageReference(field.value.type); - import_list->insert("import " + package_reference); - } - } - - void GenStructInit(const FieldDef& field, std::string* out_ptr, - std::set* import_list, - std::set* import_typing_list) const { - import_typing_list->insert("Optional"); - auto& output = *out_ptr; - const Type& type = field.value.type; - const std::string object_type = namer_.ObjectType(*type.struct_def); - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(type); - output = package_reference + "." + object_type + "]"; - import_list->insert("import " + package_reference); - } else { - output = object_type + "]"; - } - output = "Optional[" + output; - } - - void GenVectorInit(const FieldDef& field, std::string* field_type_ptr, - std::set* import_list, - std::set* import_typing_list) const { - import_typing_list->insert("List"); - auto& field_type = *field_type_ptr; - const Type& vector_type = field.value.type.VectorType(); - const BaseType base_type = vector_type.base_type; - if (base_type == BASE_TYPE_STRUCT) { - const std::string object_type = - namer_.ObjectType(*vector_type.struct_def); - field_type = object_type + "]"; - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(vector_type); - field_type = package_reference + "." + object_type + "]"; - import_list->insert("import " + package_reference); - } - field_type = "Optional[List[" + field_type + "]"; - } else { - field_type = "Optional[List[" + - GetBasePythonTypeForScalarAndString(base_type) + "]]"; - } + output.erase(output.length() - 2); + output += "]"; + return output; } - void GenInitialize(const StructDef& struct_def, std::string* code_ptr, - std::set* import_list) const { - std::string signature_params; - std::string init_body; - std::set import_typing_list; + std::string GenStructInit(const FieldDef& field, ImportMap& imports) const { + const auto& type = field.value.type; + const auto object_type = namer_.ObjectType(*type.struct_def); - signature_params += GenIndents(2) + "self,"; + imports.Add("typing", "Optional"); + imports.Add(GenPackageReference(type), object_type); - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto& field = **it; - if (field.deprecated) continue; + return "Optional[" + object_type + "]"; + } - // Determines field type, default value, and typing imports. - auto base_type = field.value.type.base_type; - std::string field_type; - switch (base_type) { - case BASE_TYPE_UNION: { - GenUnionInit(field, &field_type, import_list, &import_typing_list); - break; - } - case BASE_TYPE_STRUCT: { - GenStructInit(field, &field_type, import_list, &import_typing_list); - break; - } - case BASE_TYPE_VECTOR: - case BASE_TYPE_ARRAY: { - GenVectorInit(field, &field_type, import_list, &import_typing_list); - break; + std::string GenVectorInit(const FieldDef& field, ImportMap& imports) const { + imports.Add("typing", "List"); + + const auto& vector_type = field.value.type.VectorType(); + const auto base_type = vector_type.base_type; + + if (base_type != BASE_TYPE_STRUCT) { + return "Optional[List[" + GetBasePythonTypeForScalarAndString(base_type) + + "]]"; + } + + const auto object_type = namer_.ObjectType(*vector_type.struct_def); + + imports.Add(GenPackageReference(vector_type), object_type); + return "Optional[List[" + object_type + "]]"; + } + + std::string GetFieldType(const FieldDef& field, ImportMap& imports) const { + const auto base_type = field.value.type.base_type; + switch (base_type) { + case BASE_TYPE_UNION: + return GenUnionInit(field, imports); + case BASE_TYPE_STRUCT: + return GenStructInit(field, imports); + case BASE_TYPE_VECTOR: + case BASE_TYPE_ARRAY: + return GenVectorInit(field, imports); + default: + // Scalar or sting fields. + std::string field_type = GetBasePythonTypeForScalarAndString(base_type); + if (field.IsScalarOptional()) { + imports.Add("typing", "Optional"); + field_type = "Optional[" + field_type + "]"; } - default: - // Scalar or sting fields. - field_type = GetBasePythonTypeForScalarAndString(base_type); - if (field.IsScalarOptional()) { - import_typing_list.insert("Optional"); - field_type = "Optional[" + field_type + "]"; - } - break; - } + return field_type; + } + } + + void GenInitialize(const StructDef& struct_def, std::string* code_ptr, + ImportMap& imports) const { + std::string signature_params{GenIndents(2) + "self,"}; + std::string init_body; + std::string code; + for (const auto* field_ptr : struct_def.fields.vec) { + const auto& field = *field_ptr; + if (field.deprecated) continue; + // Determines field type and default value. + const auto field_type = GetFieldType(field, imports); const auto default_value = GetDefaultValue(field); + // Writes the init statement. const auto field_field = namer_.Field(field); @@ -1897,31 +1899,6 @@ class PythonGenerator : public BaseGenerator { code_base += init_body; } code_base += "\n"; - - // Merges the typing imports into import_list. - if (!import_typing_list.empty()) { - // Adds the try statement. - std::string typing_imports = "try:"; - typing_imports += GenIndents(1) + "from typing import "; - std::string separator_string = ", "; - for (auto it = import_typing_list.begin(); it != import_typing_list.end(); - ++it) { - const std::string& im = *it; - typing_imports += im + separator_string; - } - // Removes the last separator_string. - typing_imports.erase(typing_imports.length() - separator_string.size()); - - // Adds the except statement. - typing_imports += "\n"; - typing_imports += "except:"; - typing_imports += GenIndents(1) + "pass"; - import_list->insert(typing_imports); - } - - // Removes the import of the struct itself, if applied. - auto struct_import = "import " + namer_.NamespacedType(struct_def); - import_list->erase(struct_import); } void InitializeFromBuf(const StructDef& struct_def, @@ -1991,29 +1968,38 @@ class PythonGenerator : public BaseGenerator { } void GenUnPackForStruct(const StructDef& struct_def, const FieldDef& field, - std::string* code_ptr) const { + std::string* code_ptr, ImportMap& imports) const { auto& code = *code_ptr; - const auto struct_var = namer_.Variable(struct_def); const auto field_field = namer_.Field(field); const auto field_method = namer_.Method(field); - auto field_type = TypeName(field); + const auto pkg_ref = GenPackageReference(field.value.type); + const auto field_type = TypeName(field); + const auto obj_type = namer_.ObjectType(field_type); + const auto struct_var = namer_.Variable(struct_def); - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(field.value.type); - field_type = package_reference + "." + TypeName(field); + // Generate import statement if necessary + std::string maybe_import; + if (!imports.Contains(pkg_ref, obj_type)) maybe_import = obj_type; + if (struct_def.fixed && !imports.Contains(pkg_ref, field_type)) { + if (!maybe_import.empty()) maybe_import += ", "; + maybe_import += field_type; + } + if (!maybe_import.empty()) { + const Import import{pkg_ref, maybe_import}; + code += GenImportStatement(2, import); } code += GenIndents(2) + "if " + struct_var + "." + field_method + "("; // if field is a struct, we need to create an instance for it first. - if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) { + if (struct_def.fixed) { code += field_type + "()"; } code += ") is not None:"; - code += GenIndents(3) + "self." + field_field + " = " + - namer_.ObjectType(field_type) + +".InitFromObj(" + struct_var + - "." + field_method + "("; + + code += GenIndents(3) + "self." + field_field + " = " + obj_type + + +".InitFromObj(" + struct_var + "." + field_method + "("; // A struct's accessor requires a struct buf instance. - if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) { + if (struct_def.fixed) { code += field_type + "()"; } code += "))"; @@ -2021,19 +2007,18 @@ class PythonGenerator : public BaseGenerator { void GenUnPackForUnion(const StructDef& struct_def, const FieldDef& field, std::string* code_ptr) const { - auto& code = *code_ptr; const auto field_field = namer_.Field(field); const auto field_method = namer_.Method(field); const auto struct_var = namer_.Variable(struct_def); - const EnumDef& enum_def = *field.value.type.enum_def; - auto union_type = namer_.Type(enum_def); + const auto& enum_def = *field.value.type.enum_def; + const Import import{ModuleFor(&enum_def), + namer_.Type(enum_def) + "Creator"}; - if (parser_.opts.include_dependence_headers) { - union_type = namer_.NamespacedType(enum_def) + "." + union_type; - } - code += GenIndents(2) + "self." + field_field + " = " + union_type + - "Creator(" + "self." + field_field + "Type, " + struct_var + "." + - field_method + "())"; + auto& code = *code_ptr; + code += GenImportStatement(2, import); + code += GenIndents(2) + "self." + field_field + " = " + import.name + "(" + + "self." + field_field + "Type, " + struct_var + "." + field_method + + "())"; } void GenUnPackForStructVector(const StructDef& struct_def, @@ -2043,6 +2028,7 @@ class PythonGenerator : public BaseGenerator { const auto field_field = namer_.Field(field); const auto field_method = namer_.Method(field); const auto struct_var = namer_.Variable(struct_def); + const auto import = Field2ObjectImport(field); code += GenIndents(2) + "if not " + struct_var + "." + field_method + "IsNone():"; @@ -2050,52 +2036,19 @@ class PythonGenerator : public BaseGenerator { code += GenIndents(3) + "for i in range(" + struct_var + "." + field_method + "Length()):"; - auto field_type = TypeName(field); + const auto field_type = TypeName(field); auto one_instance = field_type + "_"; one_instance[0] = CharToLower(one_instance[0]); - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(field.value.type); - field_type = package_reference + "." + TypeName(field); - } + code += GenIndents(4) + "if " + struct_var + "." + field_method + "(i) is None:"; code += GenIndents(5) + "self." + field_field + ".append(None)"; code += GenIndents(4) + "else:"; - code += GenIndents(5) + one_instance + " = " + - namer_.ObjectType(field_type) + ".InitFromObj(" + struct_var + "." + - field_method + "(i))"; - code += - GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")"; - } - - void GenUnpackForTableVector(const StructDef& struct_def, - const FieldDef& field, - std::string* code_ptr) const { - auto& code = *code_ptr; - const auto field_field = namer_.Field(field); - const auto field_method = namer_.Method(field); - const auto struct_var = namer_.Variable(struct_def); - code += GenIndents(2) + "if not " + struct_var + "." + field_method + - "IsNone():"; - code += GenIndents(3) + "self." + field_field + " = []"; - code += GenIndents(3) + "for i in range(" + struct_var + "." + - field_method + "Length()):"; + code += GenImportStatement(5, import); - auto field_type = TypeName(field); - auto one_instance = field_type + "_"; - one_instance[0] = CharToLower(one_instance[0]); - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(field.value.type); - field_type = package_reference + "." + TypeName(field); - } - code += GenIndents(4) + "if " + struct_var + "." + field_method + - "(i) is None:"; - code += GenIndents(5) + "self." + field_field + ".append(None)"; - code += GenIndents(4) + "else:"; - code += GenIndents(5) + one_instance + " = " + - namer_.ObjectType(field_type) + ".InitFromObj(" + struct_var + "." + - field_method + "(i))"; + code += GenIndents(5) + one_instance + " = " + import.name + + ".InitFromObj(" + struct_var + "." + field_method + "(i))"; code += GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")"; } @@ -2172,19 +2125,17 @@ class PythonGenerator : public BaseGenerator { } // Generates the UnPack method for the object class. - void GenUnPack(const StructDef& struct_def, std::string* code_ptr) const { + void GenUnPack(const StructDef& struct_def, std::string* code_ptr, + ImportMap& imports) const { std::string code; - // Items that needs to be imported. No duplicate modules will be imported. - std::set import_list; - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto& field = **it; + for (const auto* field_ptr : struct_def.fields.vec) { + const auto& field = *field_ptr; if (field.deprecated) continue; switch (field.value.type.base_type) { case BASE_TYPE_STRUCT: { - GenUnPackForStruct(struct_def, field, &code); + GenUnPackForStruct(struct_def, field, &code, imports); break; } case BASE_TYPE_UNION: { @@ -2223,12 +2174,6 @@ class PythonGenerator : public BaseGenerator { code_base += GenIndents(2) + "if " + struct_var + " is None:"; code_base += GenIndents(3) + "return"; - // Write the import statements. - for (std::set::iterator it = import_list.begin(); - it != import_list.end(); ++it) { - code_base += GenIndents(2) + *it; - } - // Write the code. code_base += code; code_base += "\n"; @@ -2515,17 +2460,16 @@ class PythonGenerator : public BaseGenerator { code_base += "\n"; } - void GenStructForObjectAPI(const StructDef& struct_def, - std::string* code_ptr) const { + void GenStructForObjectAPI(const StructDef& struct_def, std::string* code_ptr, + ImportMap& imports) const { if (struct_def.generated) return; - std::set import_list; std::string code; // Creates an object class for a struct or a table BeginClassForObjectAPI(struct_def, &code); - GenInitialize(struct_def, &code, &import_list); + GenInitialize(struct_def, &code, imports); InitializeFromBuf(struct_def, &code); @@ -2537,7 +2481,7 @@ class PythonGenerator : public BaseGenerator { GenCompareOperator(struct_def, &code); } - GenUnPack(struct_def, &code); + GenUnPack(struct_def, &code, imports); if (struct_def.fixed) { GenPackForStruct(struct_def, &code); @@ -2545,13 +2489,8 @@ class PythonGenerator : public BaseGenerator { GenPackForTable(struct_def, &code); } - // Adds the imports at top. auto& code_base = *code_ptr; code_base += "\n"; - for (auto it = import_list.begin(); it != import_list.end(); it++) { - auto im = *it; - code_base += im + "\n"; - } code_base += code; } @@ -2560,16 +2499,15 @@ class PythonGenerator : public BaseGenerator { auto& code = *code_ptr; const auto union_type = namer_.Type(enum_def); const auto variant = namer_.Variant(ev); - auto field_type = namer_.ObjectType(*ev.union_type.struct_def); + const Import import{GenPackageReference(ev.union_type), + namer_.ObjectType(ev.union_type.struct_def->name)}; code += GenIndents(1) + "if unionType == " + union_type + "." + variant + ":"; - if (parser_.opts.include_dependence_headers) { - auto package_reference = GenPackageReference(ev.union_type); - code += GenIndents(2) + "import " + package_reference; - field_type = package_reference + "." + field_type; - } - code += GenIndents(2) + "return " + field_type + + + code += GenImportStatement(2, import); + + code += GenIndents(2) + "return " + import.name + ".InitFromBuf(table.Bytes, table.Pos)"; } @@ -2716,6 +2654,15 @@ class PythonGenerator : public BaseGenerator { return GenTypeGet(field.value.type); } + Import Field2Import(const FieldDef& field) const { + return {GenPackageReference(field.value.type), TypeName(field)}; + } + + Import Field2ObjectImport(const FieldDef& field) const { + return {GenPackageReference(field.value.type), + namer_.ObjectType(TypeName(field))}; + } + std::string ReturnType(const StructDef& struct_def, const FieldDef& field) const { // If we have a class member that returns an instance of the same class, @@ -2729,9 +2676,8 @@ class PythonGenerator : public BaseGenerator { // def Children(self, j: int) -> Optional['Field']: // pass // - // because Python is unable to resolve the name during parse and will return - // an error. - // (see PEP 484 under forward references: + // because Python is unable to resolve the name during parse and will + // return an error. (see PEP 484 under forward references: // https://peps.python.org/pep-0484/#forward-references) const std::string self_type = struct_def.name; std::string field_type = TypeName(field); @@ -2780,23 +2726,20 @@ class PythonGenerator : public BaseGenerator { for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end(); ++it) { auto& enum_def = **it; - std::string enumcode; - GenEnum(enum_def, &enumcode); - if (parser_.opts.generate_object_based_api & enum_def.is_union) { - GenUnionCreator(enum_def, &enumcode); + std::string code; + GenEnum(enum_def, &code); + if (parser_.opts.generate_object_based_api && enum_def.is_union) { + GenUnionCreator(enum_def, &code); } - if (parser_.opts.one_file && !enumcode.empty()) { - *one_file_code += enumcode + "\n\n"; + if (parser_.opts.one_file && !code.empty()) { + *one_file_code += code + "\n\n"; } else { - ImportMap imports; - const std::string mod = - namer_.File(enum_def, SkipFile::SuffixAndExtension); - - if (!SaveType(namer_.File(enum_def, SkipFile::Suffix), - *enum_def.defined_namespace, enumcode, imports, mod, - false)) - return false; + const auto mod = namer_.File(enum_def, SkipFile::SuffixAndExtension); + const auto def_name = namer_.File(enum_def, SkipFile::Suffix); + const auto& ns = *enum_def.defined_namespace; + + if (!SaveType(def_name, ns, code, {}, mod, false)) return false; } } return true; @@ -2811,7 +2754,7 @@ class PythonGenerator : public BaseGenerator { ImportMap imports; GenStruct(struct_def, &declcode, imports); if (parser_.opts.generate_object_based_api) { - GenStructForObjectAPI(struct_def, &declcode); + GenStructForObjectAPI(struct_def, &declcode, imports); } if (parser_.opts.one_file) { @@ -2819,54 +2762,67 @@ class PythonGenerator : public BaseGenerator { *one_file_code += declcode + "\n\n"; } - for (auto import_str : imports) { - one_file_imports.insert(import_str); - } + one_file_imports.Merge(std::move(imports)); } else { - const std::string mod = - namer_.File(struct_def, SkipFile::SuffixAndExtension); - if (!SaveType(namer_.File(struct_def, SkipFile::Suffix), - *struct_def.defined_namespace, declcode, imports, mod, - true)) - return false; + const auto mod = namer_.File(struct_def, SkipFile::SuffixAndExtension); + const auto def_name = namer_.File(struct_def, SkipFile::Suffix); + const auto& ns = *struct_def.defined_namespace; + + if (!SaveType(def_name, ns, declcode, imports, mod, true)) return false; } } return true; } // Begin by declaring namespace and imports. - void BeginFile(const std::string& name_space_name, const bool needs_imports, + void BeginFile(const Namespace& ns, const bool needs_flatbuf_imports, std::string* code_ptr, const std::string& mod, - const ImportMap& imports) const { + ImportMap imports) const { auto& code = *code_ptr; code = code + "# " + FlatBuffersGeneratedWarning() + "\n\n"; - code += "# namespace: " + name_space_name + "\n\n"; - - if (needs_imports) { - const std::string local_import = "." + mod; + code += "# namespace: " + LastNamespacePart(ns) + "\n\n"; + const auto cur_mod = namer_.Namespace(ns) + "." + mod; - code += "import flatbuffers\n"; + if (needs_flatbuf_imports) { + imports.Add("flatbuffers", {}); if (parser_.opts.python_gen_numpy) { - code += "from flatbuffers.compat import import_numpy\n"; + imports.Add("flatbuffers.compat", "import_numpy"); } - if (parser_.opts.python_typing) { - code += "from typing import Any\n"; - - for (auto import_entry : imports) { - // If we have a file called, say, "MyType.py" and in it we have a - // class "MyType", we can generate imports -- usually when we - // have a type that contains arrays of itself -- of the type - // "from .MyType import MyType", which Python can't resolve. So - // if we are trying to import ourself, we skip. - if (import_entry.first != local_import) { - code += "from " + import_entry.first + " import " + - import_entry.second + "\n"; - } - } + } + if (parser_.opts.python_typing) { + imports.Add("typing", "Any"); + } + + const std::string local_import = "." + mod; + + for (const auto& import : imports) { + const auto& imod = import.first; + const auto& types = import.second; + + // If we have a file called, say, "MyType.py" and in it we have a + // class "MyType", we can generate imports -- usually when we + // have a type that contains arrays of itself -- of the type + // "from .MyType import MyType", which Python can't resolve. So + // if we are trying to import ourself, we skip. + if (imod == local_import || imod == cur_mod) continue; + if (types.empty()) { + code += "import " + imod + "\n"; + continue; } - if (parser_.opts.python_gen_numpy) { - code += "np = import_numpy()\n\n"; + + std::string str; + for (const auto& type : types) { + str += type + ", "; } + str.erase(str.size() - 2, 2); // Remove the last ", ". + + code += "from " + imod + " import " + str + "\n"; + } + + if (needs_flatbuf_imports && parser_.opts.python_gen_numpy) { + code += "np = import_numpy()\n\n"; + } else if (!imports.Empty()) { + code += "\n"; } } @@ -2877,7 +2833,7 @@ class PythonGenerator : public BaseGenerator { if (classcode.empty()) return true; std::string code = ""; - BeginFile(LastNamespacePart(ns), needs_imports, &code, mod, imports); + BeginFile(ns, needs_imports, &code, mod, imports); code += classcode; const std::string directories = diff --git a/tests/MyGame/Example/Any.py b/tests/MyGame/Example/Any.py index 17ce5503280..ae95e9875af 100644 --- a/tests/MyGame/Example/Any.py +++ b/tests/MyGame/Example/Any.py @@ -13,12 +13,12 @@ def AnyCreator(unionType, table): if not isinstance(table, Table): return None if unionType == Any.Monster: - import MyGame.Example.Monster - return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) if unionType == Any.TestSimpleTableWithEnum: - import MyGame.Example.TestSimpleTableWithEnum - return MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.TestSimpleTableWithEnum import TestSimpleTableWithEnumT + return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) if unionType == Any.MyGame_Example2_Monster: - import MyGame.Example2.Monster - return MyGame.Example2.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example2.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) return None diff --git a/tests/MyGame/Example/AnyAmbiguousAliases.py b/tests/MyGame/Example/AnyAmbiguousAliases.py index 3a685f9a19b..155fa4e4cd8 100644 --- a/tests/MyGame/Example/AnyAmbiguousAliases.py +++ b/tests/MyGame/Example/AnyAmbiguousAliases.py @@ -13,12 +13,12 @@ def AnyAmbiguousAliasesCreator(unionType, table): if not isinstance(table, Table): return None if unionType == AnyAmbiguousAliases.M1: - import MyGame.Example.Monster - return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) if unionType == AnyAmbiguousAliases.M2: - import MyGame.Example.Monster - return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) if unionType == AnyAmbiguousAliases.M3: - import MyGame.Example.Monster - return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) return None diff --git a/tests/MyGame/Example/AnyUniqueAliases.py b/tests/MyGame/Example/AnyUniqueAliases.py index 837505e4055..e30c7e71508 100644 --- a/tests/MyGame/Example/AnyUniqueAliases.py +++ b/tests/MyGame/Example/AnyUniqueAliases.py @@ -13,12 +13,12 @@ def AnyUniqueAliasesCreator(unionType, table): if not isinstance(table, Table): return None if unionType == AnyUniqueAliases.M: - import MyGame.Example.Monster - return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) if unionType == AnyUniqueAliases.TS: - import MyGame.Example.TestSimpleTableWithEnum - return MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.TestSimpleTableWithEnum import TestSimpleTableWithEnumT + return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) if unionType == AnyUniqueAliases.M2: - import MyGame.Example2.Monster - return MyGame.Example2.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example2.Monster import MonsterT + return MonsterT.InitFromBuf(table.Bytes, table.Pos) return None diff --git a/tests/MyGame/Example/ArrayStruct.py b/tests/MyGame/Example/ArrayStruct.py index 1b0a3b27fff..bf5abc4d64e 100644 --- a/tests/MyGame/Example/ArrayStruct.py +++ b/tests/MyGame/Example/ArrayStruct.py @@ -2,10 +2,10 @@ # namespace: Example +from MyGame.Example.NestedStruct import NestedStruct, NestedStructT import flatbuffers from flatbuffers.compat import import_numpy -from typing import Any -from MyGame.Example.NestedStruct import NestedStruct +from typing import Any, List np = import_numpy() class ArrayStruct(object): @@ -105,11 +105,6 @@ def CreateArrayStruct(builder, a, b, c, d_a, d_b, d_c, d_d, e, f): builder.PrependFloat32(a) return builder.Offset() -import MyGame.Example.NestedStruct -try: - from typing import List -except: - pass class ArrayStructT(object): @@ -126,7 +121,7 @@ def __init__( self.a = a # type: float self.b = b # type: Optional[List[int]] self.c = c # type: int - self.d = d # type: Optional[List[MyGame.Example.NestedStruct.NestedStructT]] + self.d = d # type: Optional[List[NestedStructT]] self.e = e # type: int self.f = f # type: Optional[List[int]] @@ -166,7 +161,8 @@ def _UnPack(self, arrayStruct): if arrayStruct.D(i) is None: self.d.append(None) else: - nestedStruct_ = MyGame.Example.NestedStruct.NestedStructT.InitFromObj(arrayStruct.D(i)) + from MyGame.Example.NestedStruct import NestedStructT + nestedStruct_ = NestedStructT.InitFromObj(arrayStruct.D(i)) self.d.append(nestedStruct_) self.e = arrayStruct.E() if not arrayStruct.FIsNone(): diff --git a/tests/MyGame/Example/ArrayTable.py b/tests/MyGame/Example/ArrayTable.py index 09227d03072..ca6cab0d1c3 100644 --- a/tests/MyGame/Example/ArrayTable.py +++ b/tests/MyGame/Example/ArrayTable.py @@ -2,11 +2,10 @@ # namespace: Example +from MyGame.Example.ArrayStruct import ArrayStruct, ArrayStructT import flatbuffers from flatbuffers.compat import import_numpy -from typing import Any -from MyGame.Example.ArrayStruct import ArrayStruct -from typing import Optional +from typing import Any, Optional np = import_numpy() class ArrayTable(object): @@ -59,11 +58,6 @@ def ArrayTableEnd(builder: flatbuffers.Builder) -> int: def End(builder: flatbuffers.Builder) -> int: return ArrayTableEnd(builder) -import MyGame.Example.ArrayStruct -try: - from typing import Optional -except: - pass class ArrayTableT(object): @@ -72,7 +66,7 @@ def __init__( self, a = None, ): - self.a = a # type: Optional[MyGame.Example.ArrayStruct.ArrayStructT] + self.a = a # type: Optional[ArrayStructT] @classmethod def InitFromBuf(cls, buf, pos): @@ -96,7 +90,7 @@ def _UnPack(self, arrayTable): if arrayTable is None: return if arrayTable.A() is not None: - self.a = MyGame.Example.ArrayStruct.ArrayStructT.InitFromObj(arrayTable.A()) + self.a = ArrayStructT.InitFromObj(arrayTable.A()) # ArrayTableT def Pack(self, builder): diff --git a/tests/MyGame/Example/Monster.py b/tests/MyGame/Example/Monster.py index 4682113d48b..0a08e1f2f1e 100644 --- a/tests/MyGame/Example/Monster.py +++ b/tests/MyGame/Example/Monster.py @@ -2,8 +2,18 @@ # namespace: Example +from MyGame.Example.Ability import AbilityT +from MyGame.Example.Referrable import ReferrableT +from MyGame.Example.Stat import StatT +from MyGame.Example.Test import TestT +from MyGame.Example.TestSimpleTableWithEnum import TestSimpleTableWithEnumT +from MyGame.Example.Vec3 import Vec3T +from MyGame.Example2.Monster import MonsterT +from MyGame.InParentNamespace import InParentNamespaceT import flatbuffers from flatbuffers.compat import import_numpy +from flatbuffers.table import Table +from typing import List, Optional, Union np = import_numpy() # an example documentation comment: "monster object" @@ -106,7 +116,6 @@ def TestType(self): def Test(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) if o != 0: - from flatbuffers.table import Table obj = Table(bytearray(), 0) self._tab.Union(obj, o) return obj @@ -674,7 +683,6 @@ def AnyUniqueType(self): def AnyUnique(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(92)) if o != 0: - from flatbuffers.table import Table obj = Table(bytearray(), 0) self._tab.Union(obj, o) return obj @@ -691,7 +699,6 @@ def AnyAmbiguousType(self): def AnyAmbiguous(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(96)) if o != 0: - from flatbuffers.table import Table obj = Table(bytearray(), 0) self._tab.Union(obj, o) return obj @@ -1384,21 +1391,6 @@ def MonsterEnd(builder): def End(builder): return MonsterEnd(builder) -import MyGame.Example.Ability -import MyGame.Example.Any -import MyGame.Example.AnyAmbiguousAliases -import MyGame.Example.AnyUniqueAliases -import MyGame.Example.Referrable -import MyGame.Example.Stat -import MyGame.Example.Test -import MyGame.Example.TestSimpleTableWithEnum -import MyGame.Example.Vec3 -import MyGame.Example2.Monster -import MyGame.InParentNamespace -try: - from typing import List, Optional, Union -except: - pass class MonsterT(object): @@ -1467,20 +1459,20 @@ def __init__( negativeInfinityDefault = float('-inf'), doubleInfDefault = float('inf'), ): - self.pos = pos # type: Optional[MyGame.Example.Vec3.Vec3T] + self.pos = pos # type: Optional[Vec3T] self.mana = mana # type: int self.hp = hp # type: int self.name = name # type: Optional[str] self.inventory = inventory # type: Optional[List[int]] self.color = color # type: int self.testType = testType # type: int - self.test = test # type: Union[None, 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT', 'MyGame.Example2.Monster.MonsterT'] - self.test4 = test4 # type: Optional[List[MyGame.Example.Test.TestT]] + self.test = test # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT] + self.test4 = test4 # type: Optional[List[TestT]] self.testarrayofstring = testarrayofstring # type: Optional[List[Optional[str]]] - self.testarrayoftables = testarrayoftables # type: Optional[List[MyGame.Example.Monster.MonsterT]] - self.enemy = enemy # type: Optional[MyGame.Example.Monster.MonsterT] + self.testarrayoftables = testarrayoftables # type: Optional[List[MonsterT]] + self.enemy = enemy # type: Optional[MonsterT] self.testnestedflatbuffer = testnestedflatbuffer # type: Optional[List[int]] - self.testempty = testempty # type: Optional[MyGame.Example.Stat.StatT] + self.testempty = testempty # type: Optional[StatT] self.testbool = testbool # type: bool self.testhashs32Fnv1 = testhashs32Fnv1 # type: int self.testhashu32Fnv1 = testhashu32Fnv1 # type: int @@ -1495,29 +1487,29 @@ def __init__( self.testf2 = testf2 # type: float self.testf3 = testf3 # type: float self.testarrayofstring2 = testarrayofstring2 # type: Optional[List[Optional[str]]] - self.testarrayofsortedstruct = testarrayofsortedstruct # type: Optional[List[MyGame.Example.Ability.AbilityT]] + self.testarrayofsortedstruct = testarrayofsortedstruct # type: Optional[List[AbilityT]] self.flex = flex # type: Optional[List[int]] - self.test5 = test5 # type: Optional[List[MyGame.Example.Test.TestT]] + self.test5 = test5 # type: Optional[List[TestT]] self.vectorOfLongs = vectorOfLongs # type: Optional[List[int]] self.vectorOfDoubles = vectorOfDoubles # type: Optional[List[float]] - self.parentNamespaceTest = parentNamespaceTest # type: Optional[MyGame.InParentNamespace.InParentNamespaceT] - self.vectorOfReferrables = vectorOfReferrables # type: Optional[List[MyGame.Example.Referrable.ReferrableT]] + self.parentNamespaceTest = parentNamespaceTest # type: Optional[InParentNamespaceT] + self.vectorOfReferrables = vectorOfReferrables # type: Optional[List[ReferrableT]] self.singleWeakReference = singleWeakReference # type: int self.vectorOfWeakReferences = vectorOfWeakReferences # type: Optional[List[int]] - self.vectorOfStrongReferrables = vectorOfStrongReferrables # type: Optional[List[MyGame.Example.Referrable.ReferrableT]] + self.vectorOfStrongReferrables = vectorOfStrongReferrables # type: Optional[List[ReferrableT]] self.coOwningReference = coOwningReference # type: int self.vectorOfCoOwningReferences = vectorOfCoOwningReferences # type: Optional[List[int]] self.nonOwningReference = nonOwningReference # type: int self.vectorOfNonOwningReferences = vectorOfNonOwningReferences # type: Optional[List[int]] self.anyUniqueType = anyUniqueType # type: int - self.anyUnique = anyUnique # type: Union[None, 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT', 'MyGame.Example2.Monster.MonsterT'] + self.anyUnique = anyUnique # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT] self.anyAmbiguousType = anyAmbiguousType # type: int - self.anyAmbiguous = anyAmbiguous # type: Union[None, 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.Monster.MonsterT', 'MyGame.Example.Monster.MonsterT'] + self.anyAmbiguous = anyAmbiguous # type: Union[None, MonsterT, MonsterT, MonsterT] self.vectorOfEnums = vectorOfEnums # type: Optional[List[int]] self.signedEnum = signedEnum # type: int self.testrequirednestedflatbuffer = testrequirednestedflatbuffer # type: Optional[List[int]] - self.scalarKeySortedTables = scalarKeySortedTables # type: Optional[List[MyGame.Example.Stat.StatT]] - self.nativeInline = nativeInline # type: Optional[MyGame.Example.Test.TestT] + self.scalarKeySortedTables = scalarKeySortedTables # type: Optional[List[StatT]] + self.nativeInline = nativeInline # type: Optional[TestT] self.longEnumNonEnumDefault = longEnumNonEnumDefault # type: int self.longEnumNormalDefault = longEnumNormalDefault # type: int self.nanDefault = nanDefault # type: float @@ -1551,7 +1543,7 @@ def _UnPack(self, monster): if monster is None: return if monster.Pos() is not None: - self.pos = MyGame.Example.Vec3.Vec3T.InitFromObj(monster.Pos()) + self.pos = Vec3T.InitFromObj(monster.Pos()) self.mana = monster.Mana() self.hp = monster.Hp() self.name = monster.Name() @@ -1564,14 +1556,16 @@ def _UnPack(self, monster): self.inventory = monster.InventoryAsNumpy() self.color = monster.Color() self.testType = monster.TestType() - self.test = MyGame.Example.Any.AnyCreator(self.testType, monster.Test()) + from MyGame.Example.Any import AnyCreator + self.test = AnyCreator(self.testType, monster.Test()) if not monster.Test4IsNone(): self.test4 = [] for i in range(monster.Test4Length()): if monster.Test4(i) is None: self.test4.append(None) else: - test_ = MyGame.Example.Test.TestT.InitFromObj(monster.Test4(i)) + from MyGame.Example.Test import TestT + test_ = TestT.InitFromObj(monster.Test4(i)) self.test4.append(test_) if not monster.TestarrayofstringIsNone(): self.testarrayofstring = [] @@ -1583,10 +1577,11 @@ def _UnPack(self, monster): if monster.Testarrayoftables(i) is None: self.testarrayoftables.append(None) else: - monster_ = MyGame.Example.Monster.MonsterT.InitFromObj(monster.Testarrayoftables(i)) + from MyGame.Example.Monster import MonsterT + monster_ = MonsterT.InitFromObj(monster.Testarrayoftables(i)) self.testarrayoftables.append(monster_) if monster.Enemy() is not None: - self.enemy = MyGame.Example.Monster.MonsterT.InitFromObj(monster.Enemy()) + self.enemy = MonsterT.InitFromObj(monster.Enemy()) if not monster.TestnestedflatbufferIsNone(): if np is None: self.testnestedflatbuffer = [] @@ -1595,7 +1590,7 @@ def _UnPack(self, monster): else: self.testnestedflatbuffer = monster.TestnestedflatbufferAsNumpy() if monster.Testempty() is not None: - self.testempty = MyGame.Example.Stat.StatT.InitFromObj(monster.Testempty()) + self.testempty = StatT.InitFromObj(monster.Testempty()) self.testbool = monster.Testbool() self.testhashs32Fnv1 = monster.Testhashs32Fnv1() self.testhashu32Fnv1 = monster.Testhashu32Fnv1() @@ -1625,7 +1620,8 @@ def _UnPack(self, monster): if monster.Testarrayofsortedstruct(i) is None: self.testarrayofsortedstruct.append(None) else: - ability_ = MyGame.Example.Ability.AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i)) + from MyGame.Example.Ability import AbilityT + ability_ = AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i)) self.testarrayofsortedstruct.append(ability_) if not monster.FlexIsNone(): if np is None: @@ -1640,7 +1636,8 @@ def _UnPack(self, monster): if monster.Test5(i) is None: self.test5.append(None) else: - test_ = MyGame.Example.Test.TestT.InitFromObj(monster.Test5(i)) + from MyGame.Example.Test import TestT + test_ = TestT.InitFromObj(monster.Test5(i)) self.test5.append(test_) if not monster.VectorOfLongsIsNone(): if np is None: @@ -1657,14 +1654,15 @@ def _UnPack(self, monster): else: self.vectorOfDoubles = monster.VectorOfDoublesAsNumpy() if monster.ParentNamespaceTest() is not None: - self.parentNamespaceTest = MyGame.InParentNamespace.InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest()) + self.parentNamespaceTest = InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest()) if not monster.VectorOfReferrablesIsNone(): self.vectorOfReferrables = [] for i in range(monster.VectorOfReferrablesLength()): if monster.VectorOfReferrables(i) is None: self.vectorOfReferrables.append(None) else: - referrable_ = MyGame.Example.Referrable.ReferrableT.InitFromObj(monster.VectorOfReferrables(i)) + from MyGame.Example.Referrable import ReferrableT + referrable_ = ReferrableT.InitFromObj(monster.VectorOfReferrables(i)) self.vectorOfReferrables.append(referrable_) self.singleWeakReference = monster.SingleWeakReference() if not monster.VectorOfWeakReferencesIsNone(): @@ -1680,7 +1678,8 @@ def _UnPack(self, monster): if monster.VectorOfStrongReferrables(i) is None: self.vectorOfStrongReferrables.append(None) else: - referrable_ = MyGame.Example.Referrable.ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i)) + from MyGame.Example.Referrable import ReferrableT + referrable_ = ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i)) self.vectorOfStrongReferrables.append(referrable_) self.coOwningReference = monster.CoOwningReference() if not monster.VectorOfCoOwningReferencesIsNone(): @@ -1699,9 +1698,11 @@ def _UnPack(self, monster): else: self.vectorOfNonOwningReferences = monster.VectorOfNonOwningReferencesAsNumpy() self.anyUniqueType = monster.AnyUniqueType() - self.anyUnique = MyGame.Example.AnyUniqueAliases.AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique()) + from MyGame.Example.AnyUniqueAliases import AnyUniqueAliasesCreator + self.anyUnique = AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique()) self.anyAmbiguousType = monster.AnyAmbiguousType() - self.anyAmbiguous = MyGame.Example.AnyAmbiguousAliases.AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous()) + from MyGame.Example.AnyAmbiguousAliases import AnyAmbiguousAliasesCreator + self.anyAmbiguous = AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous()) if not monster.VectorOfEnumsIsNone(): if np is None: self.vectorOfEnums = [] @@ -1723,10 +1724,11 @@ def _UnPack(self, monster): if monster.ScalarKeySortedTables(i) is None: self.scalarKeySortedTables.append(None) else: - stat_ = MyGame.Example.Stat.StatT.InitFromObj(monster.ScalarKeySortedTables(i)) + from MyGame.Example.Stat import StatT + stat_ = StatT.InitFromObj(monster.ScalarKeySortedTables(i)) self.scalarKeySortedTables.append(stat_) if monster.NativeInline() is not None: - self.nativeInline = MyGame.Example.Test.TestT.InitFromObj(monster.NativeInline()) + self.nativeInline = TestT.InitFromObj(monster.NativeInline()) self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault() self.longEnumNormalDefault = monster.LongEnumNormalDefault() self.nanDefault = monster.NanDefault() diff --git a/tests/MyGame/Example/NestedStruct.py b/tests/MyGame/Example/NestedStruct.py index c53cc4c7eb0..43a6517e12c 100644 --- a/tests/MyGame/Example/NestedStruct.py +++ b/tests/MyGame/Example/NestedStruct.py @@ -4,7 +4,7 @@ import flatbuffers from flatbuffers.compat import import_numpy -from typing import Any +from typing import Any, List np = import_numpy() class NestedStruct(object): @@ -96,10 +96,6 @@ def CreateNestedStruct(builder, a, b, c, d): builder.PrependInt32(a[_idx0-1]) return builder.Offset() -try: - from typing import List -except: - pass class NestedStructT(object): diff --git a/tests/MyGame/Example/NestedUnion/Any.py b/tests/MyGame/Example/NestedUnion/Any.py index caf272720d7..cc11cd967a2 100644 --- a/tests/MyGame/Example/NestedUnion/Any.py +++ b/tests/MyGame/Example/NestedUnion/Any.py @@ -2,6 +2,8 @@ # namespace: NestedUnion +from typing import Any + class Any(object): NONE = 0 Vec3 = 1 @@ -12,9 +14,9 @@ def AnyCreator(unionType, table): if not isinstance(table, Table): return None if unionType == Any.Vec3: - import MyGame.Example.NestedUnion.Vec3 - return MyGame.Example.NestedUnion.Vec3.Vec3T.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.NestedUnion.Vec3 import Vec3T + return Vec3T.InitFromBuf(table.Bytes, table.Pos) if unionType == Any.TestSimpleTableWithEnum: - import MyGame.Example.NestedUnion.TestSimpleTableWithEnum - return MyGame.Example.NestedUnion.TestSimpleTableWithEnum.TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnumT + return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) return None diff --git a/tests/MyGame/Example/NestedUnion/Color.py b/tests/MyGame/Example/NestedUnion/Color.py index 6ba9ca1c633..57a14ad4dec 100644 --- a/tests/MyGame/Example/NestedUnion/Color.py +++ b/tests/MyGame/Example/NestedUnion/Color.py @@ -2,6 +2,8 @@ # namespace: NestedUnion +from typing import Any + # Composite components of Monster color. class Color(object): Red = 1 diff --git a/tests/MyGame/Example/NestedUnion/NestedUnionTest.py b/tests/MyGame/Example/NestedUnion/NestedUnionTest.py index e3d68855add..e643d62b67b 100644 --- a/tests/MyGame/Example/NestedUnion/NestedUnionTest.py +++ b/tests/MyGame/Example/NestedUnion/NestedUnionTest.py @@ -2,11 +2,12 @@ # namespace: NestedUnion +from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnumT +from MyGame.Example.NestedUnion.Vec3 import Vec3T import flatbuffers from flatbuffers.compat import import_numpy -from typing import Any from flatbuffers.table import Table -from typing import Optional +from typing import Any, Optional, Union np = import_numpy() class NestedUnionTest(object): @@ -93,13 +94,6 @@ def NestedUnionTestEnd(builder: flatbuffers.Builder) -> int: def End(builder: flatbuffers.Builder) -> int: return NestedUnionTestEnd(builder) -import MyGame.Example.NestedUnion.Any -import MyGame.Example.NestedUnion.TestSimpleTableWithEnum -import MyGame.Example.NestedUnion.Vec3 -try: - from typing import Union -except: - pass class NestedUnionTestT(object): @@ -113,7 +107,7 @@ def __init__( ): self.name = name # type: Optional[str] self.dataType = dataType # type: int - self.data = data # type: Union[None, 'MyGame.Example.NestedUnion.Vec3.Vec3T', 'MyGame.Example.NestedUnion.TestSimpleTableWithEnum.TestSimpleTableWithEnumT'] + self.data = data # type: Union[None, Vec3T, TestSimpleTableWithEnumT] self.id = id # type: int @classmethod @@ -141,7 +135,8 @@ def _UnPack(self, nestedUnionTest): if self.name is not None: self.name = self.name.decode('utf-8') self.dataType = nestedUnionTest.DataType() - self.data = MyGame.Example.NestedUnion.Any.AnyCreator(self.dataType, nestedUnionTest.Data()) + from MyGame.Example.NestedUnion.Any import AnyCreator + self.data = AnyCreator(self.dataType, nestedUnionTest.Data()) self.id = nestedUnionTest.Id() # NestedUnionTestT diff --git a/tests/MyGame/Example/NestedUnion/Vec3.py b/tests/MyGame/Example/NestedUnion/Vec3.py index 5157da6e7c2..1227b6d94cd 100644 --- a/tests/MyGame/Example/NestedUnion/Vec3.py +++ b/tests/MyGame/Example/NestedUnion/Vec3.py @@ -2,11 +2,10 @@ # namespace: NestedUnion +from MyGame.Example.NestedUnion.Test import Test, TestT import flatbuffers from flatbuffers.compat import import_numpy -from typing import Any -from MyGame.Example.NestedUnion.Test import Test -from typing import Optional +from typing import Any, Optional np = import_numpy() class Vec3(object): @@ -120,11 +119,6 @@ def Vec3End(builder: flatbuffers.Builder) -> int: def End(builder: flatbuffers.Builder) -> int: return Vec3End(builder) -import MyGame.Example.NestedUnion.Test -try: - from typing import Optional -except: - pass class Vec3T(object): @@ -143,7 +137,7 @@ def __init__( self.z = z # type: float self.test1 = test1 # type: float self.test2 = test2 # type: int - self.test3 = test3 # type: Optional[MyGame.Example.NestedUnion.Test.TestT] + self.test3 = test3 # type: Optional[TestT] @classmethod def InitFromBuf(cls, buf, pos): @@ -172,7 +166,7 @@ def _UnPack(self, vec3): self.test1 = vec3.Test1() self.test2 = vec3.Test2() if vec3.Test3() is not None: - self.test3 = MyGame.Example.NestedUnion.Test.TestT.InitFromObj(vec3.Test3()) + self.test3 = TestT.InitFromObj(vec3.Test3()) # Vec3T def Pack(self, builder): diff --git a/tests/MyGame/Example/StructOfStructs.py b/tests/MyGame/Example/StructOfStructs.py index f1e466c9d7e..e0619279f17 100644 --- a/tests/MyGame/Example/StructOfStructs.py +++ b/tests/MyGame/Example/StructOfStructs.py @@ -2,8 +2,11 @@ # namespace: Example +from MyGame.Example.Ability import AbilityT +from MyGame.Example.Test import TestT import flatbuffers from flatbuffers.compat import import_numpy +from typing import Optional np = import_numpy() class StructOfStructs(object): @@ -47,12 +50,6 @@ def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance) builder.PrependUint32(a_id) return builder.Offset() -import MyGame.Example.Ability -import MyGame.Example.Test -try: - from typing import Optional -except: - pass class StructOfStructsT(object): @@ -63,9 +60,9 @@ def __init__( b = None, c = None, ): - self.a = a # type: Optional[MyGame.Example.Ability.AbilityT] - self.b = b # type: Optional[MyGame.Example.Test.TestT] - self.c = c # type: Optional[MyGame.Example.Ability.AbilityT] + self.a = a # type: Optional[AbilityT] + self.b = b # type: Optional[TestT] + self.c = c # type: Optional[AbilityT] @classmethod def InitFromBuf(cls, buf, pos): @@ -88,12 +85,15 @@ def InitFromObj(cls, structOfStructs): def _UnPack(self, structOfStructs): if structOfStructs is None: return - if structOfStructs.A(MyGame.Example.Ability.Ability()) is not None: - self.a = MyGame.Example.Ability.AbilityT.InitFromObj(structOfStructs.A(MyGame.Example.Ability.Ability())) - if structOfStructs.B(MyGame.Example.Test.Test()) is not None: - self.b = MyGame.Example.Test.TestT.InitFromObj(structOfStructs.B(MyGame.Example.Test.Test())) - if structOfStructs.C(MyGame.Example.Ability.Ability()) is not None: - self.c = MyGame.Example.Ability.AbilityT.InitFromObj(structOfStructs.C(MyGame.Example.Ability.Ability())) + from MyGame.Example.Ability import Ability + if structOfStructs.A(Ability()) is not None: + self.a = AbilityT.InitFromObj(structOfStructs.A(Ability())) + from MyGame.Example.Test import Test + if structOfStructs.B(Test()) is not None: + self.b = TestT.InitFromObj(structOfStructs.B(Test())) + from MyGame.Example.Ability import Ability + if structOfStructs.C(Ability()) is not None: + self.c = AbilityT.InitFromObj(structOfStructs.C(Ability())) # StructOfStructsT def Pack(self, builder): diff --git a/tests/MyGame/Example/StructOfStructsOfStructs.py b/tests/MyGame/Example/StructOfStructsOfStructs.py index f5be2373fba..d96d6b6cbb4 100644 --- a/tests/MyGame/Example/StructOfStructsOfStructs.py +++ b/tests/MyGame/Example/StructOfStructsOfStructs.py @@ -2,8 +2,10 @@ # namespace: Example +from MyGame.Example.StructOfStructs import StructOfStructsT import flatbuffers from flatbuffers.compat import import_numpy +from typing import Optional np = import_numpy() class StructOfStructsOfStructs(object): @@ -38,11 +40,6 @@ def CreateStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, builder.PrependUint32(a_a_id) return builder.Offset() -import MyGame.Example.StructOfStructs -try: - from typing import Optional -except: - pass class StructOfStructsOfStructsT(object): @@ -51,7 +48,7 @@ def __init__( self, a = None, ): - self.a = a # type: Optional[MyGame.Example.StructOfStructs.StructOfStructsT] + self.a = a # type: Optional[StructOfStructsT] @classmethod def InitFromBuf(cls, buf, pos): @@ -74,8 +71,9 @@ def InitFromObj(cls, structOfStructsOfStructs): def _UnPack(self, structOfStructsOfStructs): if structOfStructsOfStructs is None: return - if structOfStructsOfStructs.A(MyGame.Example.StructOfStructs.StructOfStructs()) is not None: - self.a = MyGame.Example.StructOfStructs.StructOfStructsT.InitFromObj(structOfStructsOfStructs.A(MyGame.Example.StructOfStructs.StructOfStructs())) + from MyGame.Example.StructOfStructs import StructOfStructs + if structOfStructsOfStructs.A(StructOfStructs()) is not None: + self.a = StructOfStructsT.InitFromObj(structOfStructsOfStructs.A(StructOfStructs())) # StructOfStructsOfStructsT def Pack(self, builder): diff --git a/tests/MyGame/Example/TestEnum.py b/tests/MyGame/Example/TestEnum.py index 4f5f60800b9..42f939e9cba 100644 --- a/tests/MyGame/Example/TestEnum.py +++ b/tests/MyGame/Example/TestEnum.py @@ -2,6 +2,8 @@ # namespace: Example +from typing import Any + class TestEnum(object): A = 0 B = 1 diff --git a/tests/MyGame/Example/TypeAliases.py b/tests/MyGame/Example/TypeAliases.py index 4276159fde0..ee19c180415 100644 --- a/tests/MyGame/Example/TypeAliases.py +++ b/tests/MyGame/Example/TypeAliases.py @@ -4,6 +4,7 @@ import flatbuffers from flatbuffers.compat import import_numpy +from typing import List np = import_numpy() class TypeAliases(object): @@ -248,10 +249,6 @@ def TypeAliasesEnd(builder): def End(builder): return TypeAliasesEnd(builder) -try: - from typing import List -except: - pass class TypeAliasesT(object): diff --git a/tests/MyGame/Example/Vec3.py b/tests/MyGame/Example/Vec3.py index 4d5948a583e..ae0039d8740 100644 --- a/tests/MyGame/Example/Vec3.py +++ b/tests/MyGame/Example/Vec3.py @@ -2,8 +2,10 @@ # namespace: Example +from MyGame.Example.Test import TestT import flatbuffers from flatbuffers.compat import import_numpy +from typing import Optional np = import_numpy() class Vec3(object): @@ -49,11 +51,6 @@ def CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b): builder.PrependFloat32(x) return builder.Offset() -import MyGame.Example.Test -try: - from typing import Optional -except: - pass class Vec3T(object): @@ -72,7 +69,7 @@ def __init__( self.z = z # type: float self.test1 = test1 # type: float self.test2 = test2 # type: int - self.test3 = test3 # type: Optional[MyGame.Example.Test.TestT] + self.test3 = test3 # type: Optional[TestT] @classmethod def InitFromBuf(cls, buf, pos): @@ -100,8 +97,9 @@ def _UnPack(self, vec3): self.z = vec3.Z() self.test1 = vec3.Test1() self.test2 = vec3.Test2() - if vec3.Test3(MyGame.Example.Test.Test()) is not None: - self.test3 = MyGame.Example.Test.TestT.InitFromObj(vec3.Test3(MyGame.Example.Test.Test())) + from MyGame.Example.Test import Test + if vec3.Test3(Test()) is not None: + self.test3 = TestT.InitFromObj(vec3.Test3(Test())) # Vec3T def Pack(self, builder): diff --git a/tests/MyGame/MonsterExtra.py b/tests/MyGame/MonsterExtra.py index e07362ba725..85540613fcb 100644 --- a/tests/MyGame/MonsterExtra.py +++ b/tests/MyGame/MonsterExtra.py @@ -4,7 +4,7 @@ import flatbuffers from flatbuffers.compat import import_numpy -from typing import Any +from typing import Any, List np = import_numpy() class MonsterExtra(object): @@ -223,10 +223,6 @@ def MonsterExtraEnd(builder: flatbuffers.Builder) -> int: def End(builder: flatbuffers.Builder) -> int: return MonsterExtraEnd(builder) -try: - from typing import List -except: - pass class MonsterExtraT(object): diff --git a/tests/monster_test_generated.py b/tests/monster_test_generated.py index b92eab8d7a5..5c242ae3357 100644 --- a/tests/monster_test_generated.py +++ b/tests/monster_test_generated.py @@ -4,6 +4,8 @@ import flatbuffers from flatbuffers.compat import import_numpy +from flatbuffers.table import Table +from typing import List, Optional, Union np = import_numpy() # Composite components of Monster color. @@ -407,10 +409,6 @@ def CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b): builder.PrependFloat32(x) return builder.Offset() -try: - from typing import Optional -except: - pass class Vec3T(object): @@ -569,10 +567,6 @@ def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance) builder.PrependUint32(a_id) return builder.Offset() -try: - from typing import Optional -except: - pass class StructOfStructsT(object): @@ -652,10 +646,6 @@ def CreateStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, builder.PrependUint32(a_a_id) return builder.Offset() -try: - from typing import Optional -except: - pass class StructOfStructsOfStructsT(object): @@ -985,7 +975,6 @@ def TestType(self): def Test(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) if o != 0: - from flatbuffers.table import Table obj = Table(bytearray(), 0) self._tab.Union(obj, o) return obj @@ -1089,7 +1078,6 @@ def TestnestedflatbufferAsNumpy(self): def TestnestedflatbufferNestedRoot(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) if o != 0: - from MyGame.Example.Monster import Monster return Monster.GetRootAs(self._tab.Bytes, self._tab.Vector(o)) return 0 @@ -1544,7 +1532,6 @@ def AnyUniqueType(self): def AnyUnique(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(92)) if o != 0: - from flatbuffers.table import Table obj = Table(bytearray(), 0) self._tab.Union(obj, o) return obj @@ -1561,7 +1548,6 @@ def AnyAmbiguousType(self): def AnyAmbiguous(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(96)) if o != 0: - from flatbuffers.table import Table obj = Table(bytearray(), 0) self._tab.Union(obj, o) return obj @@ -1620,7 +1606,6 @@ def TestrequirednestedflatbufferAsNumpy(self): def TestrequirednestedflatbufferNestedRoot(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) if o != 0: - from MyGame.Example.Monster import Monster return Monster.GetRootAs(self._tab.Bytes, self._tab.Vector(o)) return 0 @@ -2000,10 +1985,6 @@ def MonsterEnd(builder): return builder.EndObject() -try: - from typing import List, Optional, Union -except: - pass class MonsterT(object): @@ -2079,7 +2060,7 @@ def __init__( self.inventory = inventory # type: Optional[List[int]] self.color = color # type: int self.testType = testType # type: int - self.test = test # type: Union[None, 'MonsterT', 'TestSimpleTableWithEnumT', 'MonsterT'] + self.test = test # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT] self.test4 = test4 # type: Optional[List[TestT]] self.testarrayofstring = testarrayofstring # type: Optional[List[Optional[str]]] self.testarrayoftables = testarrayoftables # type: Optional[List[MonsterT]] @@ -2115,9 +2096,9 @@ def __init__( self.nonOwningReference = nonOwningReference # type: int self.vectorOfNonOwningReferences = vectorOfNonOwningReferences # type: Optional[List[int]] self.anyUniqueType = anyUniqueType # type: int - self.anyUnique = anyUnique # type: Union[None, 'MonsterT', 'TestSimpleTableWithEnumT', 'MonsterT'] + self.anyUnique = anyUnique # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT] self.anyAmbiguousType = anyAmbiguousType # type: int - self.anyAmbiguous = anyAmbiguous # type: Union[None, 'MonsterT', 'MonsterT', 'MonsterT'] + self.anyAmbiguous = anyAmbiguous # type: Union[None, MonsterT, MonsterT, MonsterT] self.vectorOfEnums = vectorOfEnums # type: Optional[List[int]] self.signedEnum = signedEnum # type: int self.testrequirednestedflatbuffer = testrequirednestedflatbuffer # type: Optional[List[int]] @@ -2802,10 +2783,6 @@ def TypeAliasesEnd(builder): return builder.EndObject() -try: - from typing import List -except: - pass class TypeAliasesT(object): diff --git a/tests/optional_scalars/ScalarStuff.py b/tests/optional_scalars/ScalarStuff.py index 422c1337803..bcda8e2a482 100644 --- a/tests/optional_scalars/ScalarStuff.py +++ b/tests/optional_scalars/ScalarStuff.py @@ -4,6 +4,7 @@ import flatbuffers from flatbuffers.compat import import_numpy +from typing import Optional np = import_numpy() class ScalarStuff(object): @@ -508,10 +509,6 @@ def ScalarStuffEnd(builder): def End(builder): return ScalarStuffEnd(builder) -try: - from typing import Optional -except: - pass class ScalarStuffT(object):