Search code examples
pythonpython-module

Where to put shared functions in a Python Package?


I'm creating a python package for internal use & it has some internal functions that are common across other modules. For example, below function is being used at other modules -

def GetLocalImage(WebImage):
  ImageLink = WebImage.get("data-src")
  FileName = ImageLink.split("/")[-1]
  urllib.request.urlretrieve(ImageLink,FileName)
  return(FileName)

As you can see the function needs to use urllib. Below is the file structure of the package -

formatter
\ __init__.py
\ File1.py    --> It would call GetLocalImage()
\ File2.py    --> It would call GetLocalImage()

My main program uses from formatter import * statement. My questions are -

  1. What is the correct place for import urllib & the function?
  2. Do I need to modify the package structure?

Solution

  • I finally figured it out. Here's how I solved it -

    1. I kept the shared function to another file common.py
    2. In the common.py, I've import urllib.request
    3. In File1.py & File2.py, I've imported like from .common import *
    4. In the main program, it's simply import formatter
    5. In the __init__.py file, I've kept -
    from .common import *
    from .File1 import *
    from .File2 import *
    

    I think we can skip the __init__.py file (not sure). Hope this helps someone in future.