TM Forum Community

 View Only
Expand all | Collapse all

Python 3, split the current single file source code in one main file and multiple sub-files. Do I need to import common modules in all files?

  • 1.  Python 3, split the current single file source code in one main file and multiple sub-files. Do I need to import common modules in all files?

    Posted Sep 21, 2020 10:49

    I have a main.py file that includes a number of functions, classes as well as global variables (some of which are used as constants while others are used as global variables).

    (I know that as a rule the use of global variables is not a good practice but in my case there is no hazard).

    Additionally, the main.py imports a number of modules that are used either by the main.python (main function within it), or/and by the functions and classes within the main.py.

    So, I'd like to split the code into more .py files, for example move the "assistant" functions in a separate file e.g. assistantFuncts.py.

    Now, both main.py and assistantFuncts.py may use common modules, e.g. smtplib, and share common global variables

    In the above case, do I have to import smtplib in both .py files? Additionally, do I need to declare as global the shared variables used by both files, in both files? And how about the initialization of the variables?

    I expected that importing and declaring them in the main.py would be enough, but it seems that it is not...


    #General

    ------------------------------
    jain saniya
    TO BE VERIFIED
    ------------------------------


  • 2.  RE: Python 3, split the current single file source code in one main file and multiple sub-files. Do I need to import common modules in all files?

    TM Forum Member
    Posted Sep 23, 2020 04:35
    This is a TM Forum community, not necessarily the best place for general software and programming queries. You could try stackoverflow or other such communities.
    Nevertheless, perhaps the TMF resident Python expert @Henrique Rodrigues knows a quick answer to this question.​

    ------------------------------
    Jonathan Goldberg
    Amdocs Management Limited
    Any opinions and statements made by me on this forum are purely personal, and do not necessarily reflect the position of the TM Forum or my employer.
    ------------------------------



  • 3.  RE: Python 3, split the current single file source code in one main file and multiple sub-files. Do I need to import common modules in all files?

    TM Forum Member
    Posted Sep 24, 2020 09:51
    Short answer is that yes you have to import modules that you install via pip into other py files. If you don't use those modules in any of your helper functions you don't need to import them. If you want to import the functions back into main or share the files, you can import them by name directly as long as they are in the same folder.

    ------------------------------
    Lynn Scheinman
    SAP
    ------------------------------