Python Import and package with sample

  1. Everything from module in package

Create a folder structure as below

import everything from service1 but only api1 and api2

service1.pydef api1():    print('api1')def api2():    print('api2')def internal():    print('internal func')__all__ = ["api1","api2"]
first_pkg_test.pyfrom first_pkg.api.service1 import *if __name__ == “__main__”: api1() api2() #internal() #this will throw error

Import certain functions from service2 and lib

service2.py
def api3():
print('api3')
first_pkg_test.pyimport first_pkg.api.service2 as service2if __name__ == "__main__": service2.api3()
lib.pydef lib1(): print('lib1')
first_pkg_test.pyimport first_pkg.lib as libif __name__ == "__main__": lib.lib1()

Import same level py file

first_pkg_lib.pydef pkg_lib_outside():    print('pkg lib outside')
first_pkg_test.pyfrom first_pkg_lib import pkg_lib_outsideif __name__ == "__main__": pkg_lib_outside()

Consolidate everything into package level export and import *

__init__.py file (under first_pkg) :
from .lib import lib1from .api.service1 import api1, api2from .api.service2 import api3__all__ = ['lib1','api1','api2','api3']
In first_pkg_test.pyfrom first_pkg import *if __name__ == "__main__":lib1()api1()api2()api3()

Make module executable from python command

Load modules by string name

print('package1 loaded')import importlibservice = importlib.import_module('api.service1')service.api1()
Python3 first_pkg

--

--

--

A Senior Software Developer/Body builder . to help others enjoy coding and stay healthy

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Swift simplified: Understanding Typealias (Part 1)

HOW TO ACHIEVE YOUR APP COMPATIBILITY WITH IOS 13

HackTheBox Writeup— Travel

Using Semver for Docker Image Tags

Replace ProgressDialog with a progress button in your app

I Just Finished My First HTML Theme. Here’s What I’ve Learned.

Long Period Grating Thesis Writing

The IIIF eLife implementation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
LORY

LORY

A Senior Software Developer/Body builder . to help others enjoy coding and stay healthy

More from Medium

A Deep Dive Into Python Decorators

Nice living room

5 Advanced Tips on Python Functions

Java Vs Python: Which language meshes well with Data Science?

Understanding Object Instantiation and Metaclasses in Python