On Sun, Aug 02, 2020 at 03:36:44PM +0200, Sebastian M. Ernst wrote:
> Hi all,
> 
> yet another (possibly bad?) idea from day-to-day work ...
> 
> I occasionally need to import a lot of "stuff" from certain modules. The
> "stuff" is usually following a pattern. E.g. I have modules that
> (mostly) collect special exception classes and I usually need them all
> in one push - but nothing else from those modules.

When I have a similar requirement, I do something like this:

    stuff_to_import = ['SomeError', 'AnotherError']
    exec("from somemodule import %s" % ', '.join(stuff_to_import))
    del stuff_to_import

(by memory, so the details may not be exactly correct).

Another possibility is to offer the stuff to import in the library 
module:

    # somemodule.py
    errors = ['SomeError', 'AnotherError']

    # caller
    from somemodule import errors as errors
    exec("from somemodule import %s" % ', '.join(errors))
    del errors


The list of stuff to import can even be generated programmatically, by 
name or functionality:

    # the very end of somemodule.py
    errors = [name for name, obj in globals().items() 
              if isinstance(obj, type) and issubclass(obj, Exception)]


Another option:

    # Caller
    import somemodule
    globals().update({name: obj for name, obj in vars(somemodule).items()
              if isinstance(obj, type) and issubclass(obj, Exception)})


The bottom line here is that we can be far more flexible about filtered 
imports than mere wild cards in the names, and in a lot fewer lines of 
code than you've been using.



-- 
Steven
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/V6J43IRZWYDM2OWOZYN3M3B2W4U62OEQ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to