What is the correct way to import functions from other packages in python?

Asked

Viewed 940 times

1

If I create a python package, I will define a file setup.py that has more or less this format:

from setuptools import setup

setup(name='funniest',
      version='0.1',
      description='The funniest joke in the world',
      url='http://github.com/storborg/funniest',
      author='Flying Circus',
      author_email='[email protected]',
      license='MIT',
      packages=['funniest'],
      install_requires=[
          'markdown',
      ],
      zip_safe=False)

Is there any rule of good practice on how to refer in code to packages declared as dependencies?

For example in a file of my package, I should use import markdown at first. Or, when using a package function markdown should I wear markdown.x().

I will explain the motivation of the question. In R the equivalent of import is the library however this function has side-effects (it loads all functions into the user’s global environment) and should not be used within packages. No python I don’t know how it is, so I’m asked. (Read this before you vote to close)

  • You want to "compel" the person using your package to run the markdown.x() (for example) when importing the package?

  • No, I’m wondering how to best refer to the functions of a dependent package within the code of my package. In R for example, within a package we always use pacote_dependant::function() within the code of a package.

1 answer

2


This case is related to the normal use of Python packages. As your package has dependencies they will be installed with a normal package, so they will have their normal import mode as if you were developing some program.

Here are the standard Python import cases. If you are only going to use some function of a particular package, for example, the package math will use only the sqrt then it matters only her, not everything.

from math import sqrt

But it has the shape where it cares the whole package import math and throughout the script is used math.funcao to specify which one you want.

In your case for package internal functions it is recommended to import only them..

from pacote import funcao

Browser other questions tagged

You are not signed in. Login or sign up in order to post.