0

In Java, we have a main class who calls the classes and methods when needs. I'm trying to build a Python app with the same style: main file and few .py files with extra functionality.

I can import those files using

import <filename without .py>

What if I want to put all those files into a lib folder? I want to build a package for PyPI with my app.

3
  • 1
    I don't get your question. You can put files wherever you want. You can create folders (which is pretty much the same as package in Python) wherever you want. You then define setup.py file and you can gather all files into one package format (wheel or whatever). Commented Dec 1, 2016 at 12:27
  • 2
    Basic packaging tips from docs: docs.python.org/3/tutorial/modules.html#packages Is that what you look for? Commented Dec 1, 2016 at 12:30
  • I guess it may works... Thanks. Commented Dec 1, 2016 at 12:33

3 Answers 3

2
app/
  main.py
  lib/
    __init__.py
    foo.py
    bar.py

#main.py
from lib import foo
foo.SomeClass()
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your solution few days ago, and it doesn't works... I tried it now, and it works. Python is magic. Thanks!
1

First, place a __init__.py in the directory the modules are in. Then - if your directory's name is lib - import your file like below from your main file.

import lib.foo
lib.foo.hello() # Calls the hello() function in the lib/foo.py file

Comments

0

Place all Python files into your lib directory then also add a file called __init__.py in that directory. This file is to be left empty.

  1. Create a directory: mkdir lib

  2. Create an empty file in this directory: touch __init__.py

  3. Create the other modules you want to include in your package in this same directory

  4. In your shell (e.g. bash) add lib to your $PYTHONPATH:

    export PYTHONPATH="$PYTHONPATH:/path/to/lib"

  5. import all modules in lib: Be sure to be one directory level above lib, then: >>> from lib import *

1 Comment

your answer would be better if you included an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.