Can I import from a directory that starts with a dot (.) ?

M

Matthew Wilson

I want to have .foo directory that contains some python code. I can't
figure out how to import code from that .foo directory. Is this even
possible?

TIA

Matt
 
T

Terry Reedy

Matthew said:
I want to have .foo directory that contains some python code. I can't
figure out how to import code from that .foo directory. Is this even
possible?

Did you try putting '.foo' on sys.path?
 
J

Jason Scheirer

I want to have .foo directory that contains some python code.  I can't
figure out how to import code from that .foo directory.  Is this even
possible?

TIA

Matt

Yes, but it's not a particularly recommended thing to do as it is
CRAZY. You can get to it from the imp module's functions:

import imp
# Loads a file/dir named .foo or .foo.py on the sys.path, giving it
the overloaded name of foo in sys.modules
imp.load_module('foo', *imp.find_module('.foo'))
# Grab the module into the local namespace, it's been imported in the
system but not here yet
import foo

Seriously. Crazy. It looks strange and hard because it is in no way a
use case that anyone expects you to have. But it's possible.
 
G

Gary Herron

Matthew said:
I want to have .foo directory that contains some python code. I can't
figure out how to import code from that .foo directory. Is this even
possible?

TIA

Matt
Python starts up with a list of directories to search when importing.
You can append your directory to that list, and then import as you wish.

import sys
sys.path.append('/...path-to.../.foo')
import someModule # would find and import .foo/someModule.py

You may also enjoy printing the contents of sys.path to see the list of
directories Python starts with.

Gary Herron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,293
Messages
2,571,501
Members
48,189
Latest member
StaciLgf76

Latest Threads

Top