Una volta usato il seguente file init.py è possibile chiamare le funzioni nella stessa cartella che hanno nome file e funzione con lo stesso nome, basta solo chiamare il package.

Nota: Il file init.py non deve essere mai più modificato (bene e male perchè fa tutto in atomatico, ma contiene un exec alla fine del codice)


~ Es.:

project/
	+-- porva.py
	+-- myPackage/
		+-- __init__.py
		+-- function.py


porva.py

import myPackage
myPackage.function()
>>> BESTIA DIO

function.py

def function():
	print("BESTIA DIO")

init.py

import os
import importlib.util
 
# -------------------------------------------------------------------
# -------------------------------------------------------------------
 
#Get directory containing this file
dir_absolut_path = __file__.replace("\\__init__.py","")
 
#Get list of all files name ending in .py in dir
file_list = os.listdir(dir_absolut_path)
 
selected_file_list = list()
for file_name in file_list:
	if file_name[-3:] == ".py" and file_name != "__init__.py":
		selected_file_list.append(file_name[:-3])
 
#import all files in dir as foo.file_name
for file_name in selected_file_list:
	path = dir_absolut_path + "\\" + file_name + ".py"
 
	spec = importlib.util.spec_from_file_location(file_name+".py", path)
	foo = importlib.util.module_from_spec(spec)
	spec.loader.exec_module(foo)
 
	#create a list of chars that can compose file_name
	character_permitted = list()
	for i in range(48,58): #0,1,...,9
		character_permitted.append(chr(i))
	
	character_permitted.append('_')
 
	for i in range(65,91): #A,B,...,Z
		character_permitted.append(chr(i))
 
	for i in range(97,123): #a,b,...,z
		character_permitted.append(chr(i))
 
	#if the chars are from only the restricted list, execute the code
	is_code_safe_to_execute = True
	for char in file_name:
		if not (char in character_permitted):
			is_code_safe_to_execute = False
			break
 
	if is_code_safe_to_execute:
		try:
			exec(code)
		except AttributeError:
 			pass