5

I have a very simple package, which I eventually want to release through PyPI, which has a directory tree like the following:

daterangeparser/
   __init__.py
   parse_date_range.py
   test.py

parse_date_range.py defines a function called parse.

What is the easiest and most pythonic way for me to set up the package for easy importing of the parse function, and how can I do it?

At the moment I have to do from daterangeparser.parse_date_range import parse which seems rather clunky. I'd rather do from daterangeparser import parse, which seems simpler and more pythonic, but I can't seem to work out how to get this to work (do I need to put something else in __init__.py? Or, is there a better way to do this?

robintw
  • 27,571
  • 51
  • 138
  • 205

3 Answers3

6

You can simply add:

from .parse_date_range import parse

Into __init__.py to allow this usage. That's the best way.

You could also use an absolute import if you wanted:

from daterangeparser.parse_date_range import parse

Either of these options puts the parse() function into the daterangeparser namespace, which is what you want.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
1

Put the following in __init__.py:

from daterangeparser.parse_date_range import parse

Then you can import it the way you want.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
1

Do you really need parse_date_range module? The package name daterangeparser already conveys the intent, daterangeparser.parse_date_range doesn't make any sense.

You can move all the code from parse_date_range module to __init__ and then you can import parse like from daterangeparser import parse.

ronakg
  • 4,038
  • 21
  • 46
  • Is this good Python programming practice? I thought that `__init__.py` was meant to be kept for admin-type things? – robintw Apr 28 '12 at 12:05
  • Take a look at this thread - http://stackoverflow.com/questions/5831148/why-would-i-put-python-code-in-init-py-files. In your case, I think it is OK to have content of ``parse_date_range`` in ``__init__``. – ronakg Apr 28 '12 at 12:12