[Python] "import" and "from import" for same module

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    I find myself mixing both import x and from x import y forms for the same module, depending how often a particular object is used and whether it is clear which modules it comes from.

    For example I might write the following:

    import dataclasses
    from dataclasses import dataclass
    import json

    @dataclass
    class Point3D:
    x: int
    y: int
    z: int

    def to_json(self) -> str:
    return json.dumps(dataclasses.as_dict(self))


    I want json.dumps and dataclasses.as_dict to be called with their module name to avoid ambiguity e.g. with pickle.dumps and sympy.as_dict. But @dataclass clearly comes from dataclasses, making @dataclasses.dataclass redundant.

    Is there a way to write:

    import dataclasses
    from dataclasses import dataclass


    more cleanly, on a single line (semicolon doesn't count)? I would imagine something like from dataclasses import self, dataclass.

    Continue reading...

Compartilhe esta Página