How to make a package be visible for a computer

Viewed 26

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.

I tried to load my package using import mypackage and then use average(2,8) but I get message that name 'average' is not defined. It seems that my computer doesn't see my newly created package. Have I done something wrong/something is missing ?

2 Answers

This is just an issue with how you are importing. Since average is a function in functions.py, you would have to import the functions module from the mypackage package.

from mypackage import functions
functions.average(2, 8)

If you only want to call average instead of functions.average, you can use the wildcard import.

from mypackage.functions import *
average(2, 8)

Be careful with this method, however, since issues may arise with modules with similarly named functions are are imported with the wildcard import.

If you use import mypackage then you need to call the method with mypackage.mymethod() Alternatively, if you only want mymethod from mypackage, use

from mypackage import mymethod

mymethod()

Related