2

I'm really interested in creating a package in python. To do so, I watched and read several tutorials but there is always something that doesn't want to work.

What I'm doing

I created a folder package__tutorial in which I have another folder which corresponds to the name of my package - mypackage.

Folder mypackage contains two files:

  1. __init__.py - file which indicates where the package is
  2. functions.py - file which contains functions to be included into the package

In functions.py have some one basic function:

def average(x,y):
    return (x+y)/2

To summarize - my file structure is the following

package__tutorial containing mypackage containing __init__.py and functions.py.

Now - to load my package I just need to use:

from mypackage import functions

Then to use function average from this package we just need to use:

functions.average(2, 8)

However importing a file containing functions it's not so convenient for me. Is there any possibility to make this import in a standard way as to other packages ?

For example -

import numpy as np
np.linspace()

I would prefer to have exactly the same:

import mypackage as mp 
mp.average()

Is there any possibility to do so ? To do not import specific file containing functions, but just a package.

EDIT

I read the post you have given me, and in __init__.py I included:

from .functions import *

and it solved the issue. Thanks!

4
  • The __init__.py does more than just indicate where the files are
    – Sayse
    Commented Mar 10, 2021 at 9:45
  • use __init__.py Commented Mar 10, 2021 at 9:46
  • 1
    What is __init__.py for?
    – Sayse
    Commented Mar 10, 2021 at 9:46
  • Specifically, your question is answered at this answer on the above-linked question. This is a good question to ask, and I deleted my original comments because it turns out the documentation is not actually as clear about this stuff as I would have expected. It is a good question because, although it is already answered, you have asked it in a new way that is likely to match how others will search for it. Commented Mar 10, 2021 at 9:53

0

Browse other questions tagged or ask your own question.