hi… first time here… as i could find any help on this, i hope here i would find it
i came from php… there i make a heavy use of include_once
… since python execfile()
has been deprecated i created my own solution using with
, open
, compile
and exec
…
i want to do things more pythonic but i found import
very compicated with its scopes and namespaces etc. compared with php include_once
… for example in php i can make things like this:
/**** index.php ****/
function die($msg){
exit("<html><script>alert('$msg');</script></html>");
}
include_once 'db.php';
// more code
/**** db.php ****/
if !( $db = mysqli_connect($myhost, $myport, $myuser, $mypass) ){
die('database connection error');
}
// more database functions
but in python it can’t do easily (calling a parent function from included file)… so i found this solution: python - Call function from parent module in imported module - Stack Overflow
""" index.py """
def die(msg):
print(f'<some format> {msg}')
exit()
import db
if __name__ == '__main__':
# more code
""" db.py """
import index
if not ( db := pysqli_connect(myhost, myport, myuser, mypass) ): # hypothetic function
index.die('database connection error');
# more database functions
i know this could be a circular import but python skips second imports and you have this code to prevent it further: if __name__ == '__main__':
my question is… supposing my # more code
has 1000+ lines… is there a way to do the opposite?, stop and return to parent module in importing phase like this??
if __name__ != '__main__':
stop_import_and_return_to_parent
# more code with 1000+ lines
i tried with return
, break
, and continue
but all these exits and raises some like SyntaxError: 'keyword' outside loop/function
… note this is not a question about break/return loops/scopes execution in runtime but interrupt module importing in the middle earlier in importing phase (mostly to avoid large sub-scopes and indentations and keep code clear)
thanks in advance for your responses