0

So I have a following headache (basic I guess):

external_file.py:

def db_upload():
    # some upload_to_db_code
    # db_upload is a simple add to_db function from an API


def api_fetch_func():
    # some code
    # api_fetch_func is a function which gets information from an API

Scenario 1: Import outside the function which uses imported functions

from external_file import db_upload, api_fetch_func

def fetching_api_adding_db():
    db_upload(api_fetch_func())

x = 1
print(x)

Problem - even though db_upload and api_fetch_func are NOT CALLED inside external file, python still read them which takes time and I have to wait before x variable is printed in console

So even I put db_upload(api_fetch_func()) inside a function which is not called ( fetching_api_adding_db() as you can see ) and both db_upload and api_fetch_func is not called too, python still reads them.

Scenario 2 - import inside the function which uses imported functions

def fetching_api_adding_db():
    from external_file import db_upload, api_fetch_func
    db_upload(api_fetch_func())

x = 1
print(x)

Job done - I don't have to wait for python to read imported functions but I haven't seen anywhere people using imports inside functions

Any other ways to handle this? Is scenario 2 a "pythonic" and correct way of doing that? Why pyton read not called functions from external file?

Michal
  • 73
  • 5
  • " I don't have to wait for python to read imported functions" - yes, you have to, when your function gets executed for the first time. You just didn't notice, as you didn't run it... – Thierry Lathuille Nov 05 '22 at 11:58
  • 1
    Can you give more details about what's happening in scenario 1? If it's taking so long to import your functions that you're noticing, something has to be going on. Can you post a minimal, complete example of code that anyone can run that demonstrates the problem? – ndc85430 Nov 05 '22 at 11:58
  • 1
    @ThierryLathuille: It also means calling that function is a little slower every time you call it (it's not as slow as actually reimporting the files, it uses a cached version, but there's meaningful overhead in verifying it *can* use the cache, especially if any import hooks have been registered); the cost of the one-time import is usually pretty trivial, and it's the recommended way to do it unless the outside module is truly so heavyweight and unlikely to be used that it's worth paying every time costs to reimport from the cache to get that tiny benefit if it's not used. – ShadowRanger Nov 05 '22 at 14:45

0 Answers0