[Python-ideas] Class autoload
Terry Reedy
tjreedy at udel.edu
Sat Mar 3 16:24:42 EST 2018
On 3/3/2018 2:33 PM, Terry Reedy wrote:
> On 3/3/2018 12:12 PM, Jamesie Pic wrote:
>>
>> Hello everybody,
>>
>> I thought perhaps we could allow the usage of a "new" keyword to
>> instanciate an object, ie:
>>
>> obj = new yourmodule.YourClass()
>>
>> In this case, it would behave the same as from yourmodule import
>> YourClass; obj = YourClass(), except that it wouldn't need to be
>> imported. This would also eliminate the need to manage an import list
>> at the beginning of a script in most case.
>
> If you really want this (untested):
>
> def autoload(mod, cls, *args, **kwargs):
> from mod import cls
The make the above work with variables:
import importlib # put at top of file
mod = importlib.import_module(mod)
cls = mod.getattr(cls)
> return cls(*args, **kwargs)
>
> obj = autoload(yourmodule, YourClass)
>
--
Terry Jan Reedy
More information about the Python-ideas
mailing list