pythongoogle-style-guide

Avoiding huge files when following python google-style-guide


Google style guide requires to import modules. Say I have a non trivial class and several non-trivial derived classes. It seems that I have to put them all in the one file otherwise will have to use different prefixes when using them.

Personally I prefer one class per file. Is there a common idiom to avoid unnecessary large files?

E.g. can I rename several imports into one as long as there is no name conflicts?

import data_main as data
import data_derived_a as data
import data_derived_b as data

Solution

  • With modules, no, there's really no way of doing this that I know of. If you're happy to put your class in separate files within a package, though, you can import the individual classes in __init__.py, and your client modules can import them all at once, like so.

    # mypackage/a.py
    class A:
        pass
    
    # mypackage/b.py
    class B:
        pass
    
    # mypackage/__init__.py
    from .a import A
    from .b import B
    
    # mymodule.py
    from mypackage import A, B
    a = A()
    b = B()
    
    # Or mymodule.py
    import mypackage as p
    a = p.A()
    b = p.B()