0

I'm just learning about modules in python 3.5. While I can usually install and import packages using sudo pip install {package}, I can't seem to figure out how to import my own files.

I made a test.py file with a single definition to test. I saved it to the site-packages folder. I can't seem to import from there. I need help understanding how to import files.

I read online about possibly using sys.path however, I don't know how that works.

2
  • NOTE: You don't want to do this if you intend for other people to use your program; otherwise you're fine.
    – AMACB
    Commented Jan 25, 2016 at 1:40
  • keep your modules in your folder - and copy/paste to your project.
    – furas
    Commented Jan 25, 2016 at 1:46

1 Answer 1

1

If I had the following file structure:

/home/foo
/home/foo/__init__.py
/home/foo/bar.py

and I wanted to

import foo.bar
foo.bar.somefn()

I would first need to do:

import sys
sys.path.append("/home/foo")

Notice the init.py file, which tells python to look for submodules. We don't necessarily need it in this instance, but it's good practice to have:

What is __init__.py for?

However, since this can get repetitive, daunting and tough to track, there are lots of tools available to help you setup as your code expands to have dependencies and lots of files/folders. I suggest you read a bit about pip/disttools/easy-install and how to make a package with a 'setup.py'.

What is setup.py?

In addition, you might want to explore the world of Virtual Environments and deployment solutions such as Buildout and Anaconda. These help keep the code separated as you have several projects on the go with different needs, or even different python builds and platform requirements. When it comes time to deploy your code to other machines, you'll have a much easier time replicating the needs of the project.

Below is a series of articles with info explaining everything from packages, pip and setup.py to starting up your work environment with Buildout. Seems like a great series:

http://reinout.vanrees.org/weblog/tags/softwarereleasesseries.html

The official docs for making a setup.py:

https://docs.python.org/3/distutils/setupscript.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.