python / cpython

The Python programming language
https://www.python.org
Other
63.19k stars 30.26k forks source link

Syntactic sugar for creating factory classes #100296

Closed omrihaber closed 1 year ago

omrihaber commented 1 year ago

Feature or enhancement

When creating a factory (class that conforms to some abstract class and instantiates subclasses by providing some distinguishing attribute).

*written code I'm not sure will work as is but to indicate the idea why such syntactic sugar will be useful. Current implementation iv'e encountered when implementing this behaviour in python:

class FactoryInterface(ABC):
  def __init__(*args, **kwargs):
    pass

attribute_to_constructor:[] = { "default":someConstructor}

class Factory(FactoryInterface):
  def __new__(cls,*args,__distinguishing_attribute:str="default",**kwargs):
    if distinguishing_attribute in attribute_to_constructor:
      return attribute_to_constructor[__distinguishing_attribute:str](*args,**kwargs)

Pitch

Required input: Abstract class interface Distinguishing keys mapping/list(keys that map to constructors)

Desired output: Class that recieves the distinguishing attribute and its constructor passes its arguments to the mapped constructor.

example interface in python:

class FactoryInterface(ABC):
  def __init__(*args, **kwargs):
    pass

 sub_constructors = [a,b,c] # a,b,c are constructors  of classes inheriting/conforming to FactoryInterface

#by default map by variable(constructor/class) name or if not possible enforce name mapping

# functional way to create:
Factory:FactoryInterface = FactoryGenerator(sub_constructors,name_mapping:Optional[List]=None)

# class way:

class Factory(FactoryGenerator):
  a = constructorA
  b = constructorB
#properties names will be mapped to the constructor objects

a_instance = Factory('a')
b_instance = Factory('b')

Previous discussion

AlexWaygood commented 1 year ago

Thanks for the feature proposal! The bar for having new ideas accepted into the stdlib is quite high, however, so ideas like this need to be discussed at https://discuss.python.org/c/ideas/6 before opening an issue here. Once it's been discussed there for a while, if the idea has a reasonable level of support, we can potentially reopen this issue.

omrihaber commented 1 year ago

@AlexWaygood ty!, I will open a topic for discussion there.