Organising packages/modules - importing functions from a common.py in a separate directory?

Victor Hooi victorhooi at gmail.com
Tue Oct 29 02:58:15 EDT 2013


Hi,

Hmm, this post on SO seems to suggest that importing from another sibling directory in a package ins't actually possibly in Python without some ugly hacks?

http://stackoverflow.com/questions/6323860/sibling-package-imports

Did I read the above correctly?

Is there another way I can structure my code so that I can run the sync_em.py and sync_pg.py scripts, and they can pull common functions from somewhere?

Cheers,
Victor

On Tuesday, 29 October 2013 12:08:10 UTC+11, Victor Hooi  wrote:
> Hi,
> 
> 
> 
> If I try to use:
> 
> 
> 
>     from .common.common_foo import setup_foo_logging
> 
> 
> 
> I get:
> 
> 
> 
>     ValueError: Attempted relative import in non-package
> 
> 
> 
> And the absolute imports don't seem to be able to find the right modules.
> 
> 
> 
> Is it something to do with the fact I'm running the sync_em.py script from the "foo_loading/em_load" directory?
> 
> 
> 
> I thought I could just refer to the full path, and it'd find it, but evidently not...hmm.
> 
> 
> 
> Cheers,
> 
> Victor
> 
> 
> 
> On Tuesday, 29 October 2013 12:01:03 UTC+11, Ben Finney  wrote:
> 
> > Victor Hooi <victorhooi at gmail.com> writes:
> 
> > 
> 
> > 
> 
> > 
> 
> > > Ok, so I should be using absolute imports, not relative imports.
> 
> > 
> 
> > 
> 
> > 
> 
> > I'd say it is fine to use relative imports, so long as they are
> 
> > 
> 
> > explicit. (In Python 3, the default for an import is to be absolute, and
> 
> > 
> 
> > the *only* way to do a relative import is to make it explicitly
> 
> > 
> 
> > relative. So you may as well start doing so now.)
> 
> > 
> 
> > 
> 
> > 
> 
> > > Hmm, I just tried to use absolute imports, and it can't seem to locate
> 
> > 
> 
> > > the modules:
> 
> > 
> 
> > >
> 
> > 
> 
> > > In the file "foo_loading/em_load/sync_em.py", I have:
> 
> > 
> 
> > >
> 
> > 
> 
> > >     from common.common_bex import setup_foo_logging
> 
> > 
> 
> > 
> 
> > 
> 
> > So I'd recommend this be done with an explicit relative import:
> 
> > 
> 
> > 
> 
> > 
> 
> >     from .common.common_bex import setup_foo_logging
> 
> > 
> 
> > 
> 
> > 
> 
> > or, better, import a module:
> 
> > 
> 
> > 
> 
> > 
> 
> >     from .common import common_bex
> 
> > 
> 
> > 
> 
> > 
> 
> > or a whole package:
> 
> > 
> 
> > 
> 
> > 
> 
> >     from . import common
> 
> > 
> 
> > 
> 
> > 
> 
> > -- 
> 
> > 
> 
> >  \         “I went over to the neighbor's and asked to borrow a cup of |
> 
> 
> >   `\       salt. ‘What are you making?’ ‘A salt lick.’” —Steven Wright |
> 
> > 
> 
> > _o__)                                                                  |
> 
> > 
> 
> > Ben Finney



More information about the Python-list mailing list