pythonpython-3.xnestedclass-factory

How to access class within a method in Python


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?


Solution

  • There is no way to "import" your class from outside the function, because in reality, there is no one Package type. Every time you call make_package(), it's creating a new type, which happens to have the same name as all the other Package types. However, it is still a unique type, so it will never compare equal to another Package type, even if origin and destination are the same.

    You could make all Package types inherit from a "marker" class, and then use isinstance to check if an item is a package:

    # project/package.py
    class PackageMarker:
        pass
    
    def make_package(ori, dest):
        class Package(PackageMarker):
            ...  # Package body here
        return Package
    
    # project/shipment.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 not isinstance(item, PackageMarker):
                        raise TypeError('Item must be packed in Package.')
                    self.shipment[container].append(item.to_str())
    

    In my opinion, the way you are creating classes with this factory function is confusing, but perhaps I simply need more context to see why you're doing it this way.

    If you want my opinion on how I would refactor it, I would remove the factory function, and do something like this:

    # project/package.py
    class Package:
        def __init__(self, route, item):
            self.route = route
            self.item = item
    
        def to_str(self):
            return self.route.to_str() + ' : ' + self.item
    
    # project/route.py
    class Route:
        def __init__(self, origin, destination):
            self.origin = origin
            self.destination = destination
    
        def to_str(self):
            return self.origin + ' - ' + self.destination
    
    # project/shipment.py
    from .package import Package
    
    class Shipment:
        def __init__(self, **kwargs):
            self.shipment = dict()
            for container in kwargs.keys():
                self.shipment[container] = list()
                for item in kwargs[key]:
                    if not isinstance(item, Package):
                        raise TypeError('Item must be packed in Package.')
                    self.shipment[container].append(item.to_str())
    
    # project/main.py
    from .package import Package
    from .route import Route
    from .shipment import Shipment
    us_fr = Route('US', 'FR')
    fr_cn = Route('FR', 'CN')
    shipment = Shipment(
        container1=[Package(us_fr, 'item1'), Package(fr_cn, 'item2')],
        container2=[Package(us_fr, 'item3'), Package(fr_cn, 'item4')]
    )