Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to write package for easy importing

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?

like image 836
robintw Avatar asked Apr 28 '12 11:04

robintw


1 Answers

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.

like image 125
Gareth Latty Avatar answered Sep 28 '22 04:09

Gareth Latty