Skip to content

Conversation

@amritamishra01
Copy link

Summary

This PR fixes an issue where import statements with aliases (e.g., import numpy as np) would load the module correctly but fail to register the alias (np) in the current scope. As a result, subsequent code using the alias (like np.array()) would fail with NameError: 'np' is not defined.

This patch updates the semantic analysis phase to ensure import aliases are correctly created and installed into the symbol table as ExternalSymbols.

Technical Changes

  • Modified visit_Import in src/lpython/semantics/python_ast_to_asr.cpp:
    • Refactored the logic to merge module name extraction and module loading into a single loop.
    • Previously, these were handled in separate loops, causing the alias information (x.m_names[i].m_asname) to be lost before the symbol registration step.
  • Implemented Alias Registration:
    • Added logic to check for the presence of an alias.
    • If an alias exists, the compiler now creates an ASR::ExternalSymbol_t in the current scope.
    • This symbol maps the alias name (e.g., np) to the loaded module symbol (e.g., numpy), mirroring Python's behavior.

Verification

I verified the fix using the following reproduction script repro.py:

import numpy as np
print(np.array([1, 2, 3]))

Before Fix: Compiling failed with: semantic error: NameError: 'np' is not defined

After Fix: The compiler successfully resolves the alias. Running with --show-asr confirms the creation of the ExternalSymbol:
np:
        (ExternalSymbol
            2
            np
            1 numpy
            numpy
            []
            numpy
            Public
        )
Fixes #2814

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant