Hi Etienne,

Already tried what you are describing. Indeed it's inconvenient, and sometimes the changes in the class code did not end up in the class definition. For example, a newly defined function on the class was unknown in script_1. Might be a bug, but I'm not even sure.

So the best way should be to tell QGIS to run another python script in the console. Or go the plugin way.

Thanks and kind regards,

Raymond


On 04-05-2023 11:29, Etienne Trimaille wrote:
If you are talking about the simple Python console panel, and loading Python files from there, then you can skip the " from .script_2 import TestClass".

If you notice, when you launch the script_2.py, you have a generated line similar to :
exec(Path('/tmp/tmp5g244g4w.py').read_text())

So it's reading and executing all the content of file 2 in the console context already. So then, when file 1 will be executed, there will already be the class TestClass in the console context.

But, then to manage multiple files, it's not convenient. You should think about the smallest plugin, for instance https://github.com/wonder-sk/qgis-minimal-plugin <https://github.com/wonder-sk/qgis-minimal-plugin> Otherwise, it's difficult to manage IMHO.

Le jeu. 4 mai 2023 à 08:59, Raymond Nijssen via QGIS-Developer <qgis-developer@lists.osgeo.org <mailto:qgis-developer@lists.osgeo.org>> a écrit :

    Hi developers,

    While writing a python script in the QGIS python console editor I
    needed
    to write a new class and for convenience I put that in its own
    python file.

    Both files are in the same directory, but I cannot import my class in
    the other script.

    Here's an example:


    # script_1.py

    from .script_2 import TestClass
    obj1 = TestClass('Ray')
    print(obj1)




    # script_2.py:

    class TestClass():

          def __init__(self, name):
    self.name <http://self.name> = name

          def __str__(self):
              return f'TestClass[{self.name <http://self.name>}]'



    It all works properly if I put my class definition in script_1 but as
    the code is growing (and a customer of mine needs to understand this
    too) it would really be nice to split the code over multiple files.
    Is there a way? Or another approach?

    Kind regards,
    Raymond
    _______________________________________________
    QGIS-Developer mailing list
    QGIS-Developer@lists.osgeo.org <mailto:QGIS-Developer@lists.osgeo.org>
    List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer
    <https://lists.osgeo.org/mailman/listinfo/qgis-developer>
    Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer
    <https://lists.osgeo.org/mailman/listinfo/qgis-developer>

_______________________________________________
QGIS-Developer mailing list
QGIS-Developer@lists.osgeo.org
List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer
Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer

Reply via email to