Skip to content

Reduce number of imports inside functions #1575

Description

@Sevans711

Current behavior:

There are some places throughout the uxarray codebase where import is being used inside functions. The benefit is that the imports are "lazy"; they aren't evaluated until that function actually gets called. This is useful for optional dependencies (see also #1548) but also for any "heavy" dependencies which take a long time or a lot of memory to import. However, the downside is that the code is a bit harder to read and a bit harder to extend, as the import statements get repeated across many functions in the same file.

Proposed change:

Imports which are not "heavy" or which are already being imported non-lazily somewhere in uxarray should be changed to consistently be imported non-lazily everywhere in uxarray.

For example, many functions inside uxarray.core.api are currently doing:

def core_api_function(...):
    import xarray as xr
    ...

However in various places, such as uxarray.core.dataarray, xarray is already being imported at the top of file.

Unless there is a compelling reason to avoid importing xarray at the top of uxarray.core.api, I would propose to move these imports to the top of the file. I don't think this will reduce efficiency in any meaningful use-case, and it should help make the code easier to extend. Although, if there is a compelling reason to keep the import inside the functions instead, I would instead propose that a comment be added to each such import at least once per file to explain the reasoning.

Note: it probably makes sense to delay this work until after #1548, which also relocates some import statements.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

developer experienceMakes the codebase easier to read, debug, maintain, or extend.

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions