Question: I am using Popen to run a command but I don't know how I can write a callback that gets called once the command is finished. Any idea?

Thanks.
Bin

Answer: 
A free-standing function `def PersonFactory(name, gender):` is fine, though packaging it up as a classmethod, as @Ned suggests, shouldn't hurt (in this particular case it won't help much either, since the exact class of person to instantiate must vary). I think the cleanest implementation is in fact as a free-standing function, just because I prefer a classmethod to return instances of the class it's called on (rather than, of some other class) -- but this is a stylistic point that cannot be said to be sharply defined either way.

I'd code it (with some assumptions which I hope as clear, e.g. the gender is coded as `M` or `F` and if not specified is heuristically inferred from the name, &c):

```
def gender_from_name(name): ...

person_by_name = {}

class_by_gender = {'M': Man, 'F': Woman}

def person_factory(name, gender=None):
  p = person_by_name.get(name)
  if p is None:
    if gender is None:
      gender = gender_from_name(name)
    p = person_by_name[name] = class_by_gender[gender](name)
  return p

```
The easiest way is probably to use builtin lru\_cache from functools on `__new__`.

```
import functools

class Person:
    gender = 'unknown'
    @functools.lru_cache(maxsize=None)
    def __new__(cls, full_name):
        names = first, last = full_name.split()
        for subclass in cls.__subclasses__():
            if first in subclass.names:
                cls = subclass
        self = super().__new__(cls)
        self.first, self.last = names
        return self

class Woman(Person):
    gender = 'female'
    names = {*'Mary Linda Susan'.split()}

class Man(Person):
    gender = 'male'
    names = {*'Tom Dick Harry'.split()}

```