fsociety
fsociety

Reputation: 1027

Python package basics

I have a python file named as test1.py. This file contains few classes and a few functions.

I intend to package this and distribute so that others can use it via the pip install command. From other posts, I understood how we build a package.

Q: When the package is imported in the end user's code, using the import <mypackage> command,

1. can the functions be called directly by simply writing the function name?

2. methods which are part of the class, are ideally called by objectname.methodname, how will they be called now?

Upvotes: 0

Views: 61

Answers (2)

S2C
S2C

Reputation: 53

functions will be appended to the package name. For example:

import numpy
# Calling the square root function from numpy
val = 4
newVal = numpy.sqrt(val)

# You can also do this, but it is not recommended as it pollutes your name space 
from numpy import sqrt

# Now I can call sqrt directly
val = 4
newVal = sqrt(val)

Class methods work similarly.

Upvotes: 0

rinkert
rinkert

Reputation: 6863

It depends on how you import the package. If you import the package as

import test1

you will have to call all the classes and functions with test1.function(). The class methods like test1.objectname.methodname()

If you use

from test1 import *

you can just use the function names, but your namespace is being polluted with all the function names.

You can also import only specific functions or classes using

from test1 import function1, function2, class1, class2

To call them with just their respective name.

And lastly you can use import test1 as t1 to make it a bit shorter, calling functions can then be done using t1.function1()

Upvotes: 1

Related Questions