I have a function make_package returning a class Package. In another file, I want to import class Package, so I can do type check. My question is, how to import a class that's inside a function?
Following is not the exact code, but similar in structure.
# project/package.py
def make_package(ori, dest):
class Package:
origin = ori
destination = dest
def __init__(self, item):
self.item = item
def to_str(self):
return self.origin + '-' + self.destination + ' : ' + self.item
return Package
# project/shipment.py
# Don't know how to import Package from package.py
class Shipment:
def __init__(self, **kwargs):
self.shipment = dict()
for container in kwargs.keys():
self.shipment[container] = list()
for item in kwargs[key]:
if type(item) != Package:
raise TypeError('Item must be packed in Package.')
self.shipment[container].append(item.to_str())
# project/main.py
from .package import make_package
from .shipment import Shipment
us_fr = make_package('US', 'FR')
fr_cn = make_package('FR', 'CN')
shipment = Shipment(container1=[us_fr('item1'), fr_cn('item2')], container2=[us_fr('item3'), fr_cn('item4')])
print(shipment.shipment)
# {
# 'container1' : [
# 'US-FR : item1',
# 'FR-CN' : 'item2'
# ],
# 'container2' : [
# 'US-FR : item3',
# 'FR-CN' : 'item4'
# ]
# }
I know one way I can achieve type check is make a dummy variable with make_package inside Shipment, then compare type(item) to type(dummy). However it seems more like a hack. I wonder if there's a better way?
Packageoutside of the function. Unless you are going to usemake_packageas a factory function in the future, you don't even need that function.orianddestvalue from the function, but only create object withitem. This way I can reuse the variable, in example,us_frmany times, since I will be use it a lot more later on. If I put the class outside, I probably have to pass 3 arguments__init__(ori, dest, item)every time. Which later makes the code super messy.Packageinherit frommake_package's parameters. It gets really messy if I createPackageobject with all those parameters every time. I feel like it's way cleaner if I can usemake_packageto assign those params first, then only pass initemwhen create new instance, sinceitemis the only variable that's different every time.functools.partialto bind the common parameters to make a constructor that only needsitemwork? That would keepPackagea singleton, while still letting you have simplified interfaces that construct it with common data.