epogrebnyak / data-rosstat-kep

Time series dataset of Rosstat Short-term Economic Indicators ("KEP") publication
http://www.gks.ru/wps/wcm/connect/rosstat_main/rosstat/ru/statistics/publications/catalog/doc_1140080765391
6 stars 6 forks source link

relative import question #46

Closed epogrebnyak closed 8 years ago

epogrebnyak commented 8 years ago

https://github.com/epogrebnyak/rosstat-kep-data/blob/as_packages/src_module/kep/kep.py

running python kep.py fails with

[Anaconda3] C:\Users\Евгений\Documents\GitHub\rosstat-kep-data\src_module\kep>python -m kep
Traceback (most recent call last):
  File "C:\Users\Евгений\Anaconda3\lib\runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Евгений\Anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Евгений\Documents\GitHub\rosstat-kep-data\src_module\kep\kep.py", line 3, in <module>
    from converter.word import foo
  File "C:\Users\Евгений\Documents\GitHub\rosstat-kep-data\src_module\kep\converter\word.py", line 20, in <module>
    from ..io import dump_iter_to_csv
ValueError: attempted relative import beyond top-level package
gabrielelanaro commented 8 years ago

In this project the module structure is as follows:

src_module is the top-level package, and any absolute import should start from that or you can get inconsistent behaviour.

So in kep.py the correct reference would be from src_module.kep.converter.word import foo

If src_module is not installed system-wide (or the project root is not on PYTHONPATH), then you have to call kep.py like this:

set PYTHONPATH=.
python src_module\kep\kep.py

Or you can just move the script to the top-level directory:

copy python src_module\kep\kep.py
python kep.py
epogrebnyak commented 8 years ago

is copy python src_module\kep\kep.py correct? what is it intended to do?

epogrebnyak commented 8 years ago

also is something like below an antipattern?

try:
    from .common import dump_iter_to_csv
except (ImportError, SystemError):
     from common import dump_iter_to_csv
gabrielelanaro commented 8 years ago

Sorry, I made a mistake, the copy statement was meant to be:

copy src_module\kep\kep.py kep.py

That was just to suggest the alternative of moving the script in a more conventient location (but I don't know if that's what you want).

I would consider the try/except code to be an antipattern, If I had to run an internal module I'd rather use the -m syntax, while if it was a command-line script I'd use absolute imports.