0

I'm trying to import a package in which one of the namespaces is the keyword 'import'. How is it best to do this? Would the folder need to be renamed?

Example:

import protobuf.import.import_enum_pb2 as importEnum

This gives an invalid syntax error.

I have started to look at using __ import __ function instead-but wondered if there is a better workaround I haven't found a quotation or escaping method that works.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Trapped
  • 36
  • 4
  • Did you name that package, or is it outside your control? Because that's absolutely terrible and should not be done. Like ever. – Mad Physicist Feb 09 '21 at 21:13

2 Answers2

1
foo_bar = __import__("foo bar")

Also see https://stackoverflow.com/questions/9123517/how-do-you-import-a-file-in-python-with-spaces-in-the-name#:~:text=4%20Answers&text=You%20should%20take%20the%20spaces,supported%20by%20the%20import%20statement.&text=This%20will%20import%20foo%20bar.py%20as%20foo_bar%20.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Thank you, the problem with that is it will only take the first namespace so when nested it from the example that would just return "protobuf" – Trapped Jan 18 '21 at 13:33
  • 1
    Ah I think you're trying to do a 'relative' import. I don't have prior experience with this subject but this is what I found: If I interpret this correctly, you should do as follows: `import protobuf` `import "import.protobuf.import_enum_pb2"` # a.proto package foo; import "b.proto"; import "sub/c.proto"; import "sub/sub/d.proto"; Have you tried the documentation on this? Maybe this makes more sense to you than me? https://developers.google.com/protocol-buffers/docs/proto3#importing_definitions – Wouter Dijks Jan 18 '21 at 15:11
1

Have found this can be done using importlib

Example:

errorseverity = importlib.import_module(' protobuf.import.import_enum_pb2')

importlib see documentation: https://docs.python.org/3/library/importlib.html#importlib.import_module

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Trapped
  • 36
  • 4