[Python] Importing Python modules from different directories

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

  1. Stack

    Stack Membro Participativo

    I have the following folder setup

    user_test.py
    factories/
    user_factory.py
    pb/
    user_pb2.py
    user_pb2_grpc.py


    This is how the imports are in each of the files

    user_test.py
    import factories.user_factory

    factories/user_factory.py
    import pb.user_pb2_grpc

    pb/user_pb2_grpc.py
    import user_pb2


    However, on the last line I get an error saying

    ModuleNotFoundError: No module named 'user_pb2'

    pb/user_pb2_grpc.py is not being able to import user_pb2.py even though they are in the same directory

    This can be fixed by changing import user_pb2 to from . import user_pb2 but this is Autgenerated code by GRPC and I cannot change.

    How can I resolve this error or better structure my code?

    Continue reading...

Compartilhe esta Página