0

I study many answers on similar questions (opening same name modules that is trivial) but I not found answer to this question how to open module with same file name as __main__ program.

Let see my code tree (it is simplified for this purpose):

<source root>
  log_parser/
    log_parser.py (module to import)
  my_system/ 
    log_parser/
      log_parser.py (__main__)

As you see on the tree I want to import log_parser/log_parser. <source root> is added to path.

Python adds to path current path as first. I found that I can exclude current path from import paths and this works. Is there and alternative solution more pythonic?

<other imports>

sys.path = sys.path[1:]

from log_parser.log_parser import LogParser

How to import without monkey like that sys.path = sys.path[1:] or del sys.path[0]?

I can rename modules but I do not want ugly and too long names like my_system_log_parser.my_system_log_parser.

Chameleon
  • 9,722
  • 16
  • 65
  • 127
  • 1
    Have a look at this: https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – tituszban Aug 19 '19 at 16:14
  • This seems like a naming issue more than a coding issue (as your edit suggests you've already considered), so I'll comment rather than answer. In python, self-documenting code means having descriptive naming conventions. If it were me, I would have the names reflect what the script is actually doing (`log_parser.LogParser` for the module, then `local_project` for the local script). – G. Anderson Aug 19 '19 at 16:17
  • @tituszban Probably can be used but syntax in less readable that path patching. – Chameleon Aug 20 '19 at 09:55
  • @G.Anderson Code source/base will be very large so I can not use simple names convention by design. Consider that I will code 'abstract layer' than I wil code 2-3 'project/system layers' than I will code 2-3 tool per project. Abstract layer will bring generic functions, project layer will extend base class into many specific classes for each type of log for project that I will write some tool in project/system. You can assume that I will do universal log parser than more specific parsers and finally tools running parsers in parallel. For one system and simple log I will write simpler code. – Chameleon Aug 20 '19 at 10:02
  • So structure is: abstract parser -> specific system -> many specific parsers -> specific system tools. I prefer log_parser.BaseLogParser -> sys_name.log_parser -> BaseFormat1Parser, BaseFormat2Parser -> Service1FormatParser, Service2Format1Parser, Service3Format1Parser ... - this ugly names is only to show number of variations I will find better names. That is why I want have two modules with log_parser, project_name.log_parser names. Not log_parser and project_name_log_parser. – Chameleon Aug 20 '19 at 10:09

0 Answers0