Skip to content

Improve SyntaxError message for import a as b.c #123539

Closed

Description

@sobolevn

Feature or enhancement

Right now it shows:

>>> import a as b.c
  File "<unknown>", line 1
    import a as b.c
                 ^
SyntaxError: invalid syntax

Proposed message:

>>> import a as b.c
  File "<unknown>", line 1
    import a as b.c
                ^^^
SyntaxError: cannot use import statement with attribute

Refs #123440

I have a PR ready.

Linked PRs

Activity

  1. self-assigned this
    on Aug 31, 2024
  2. lysnikolaou commented on Sep 2, 2024

    @lysnikolaou
    Member

    I'd love to review a PR for this!

  3. sobolevn commented on Sep 2, 2024

    @sobolevn
    MemberAuthor

    It is not that easy as previous two :)
    I would take some extra time to get this right!

  4. lysnikolaou commented on Sep 3, 2024

    @lysnikolaou
    Member

    Oh right. You probably have to do something more complex than what was in the other two cases. Maybe something like this would work?

    dotted_as_name[alias_ty]:
        | a=dotted_name 'as' b=NAME &(',' | NEWLINE) { _PyAST_alias(a->v.Name.id, b->v.Name.id, EXTRA) }
        | invalid_dotted_as_name
        | a=dotted_name { _PyAST_alias(a->v.Name.id, NULL, EXTRA) }
    
    invalid_dotted_as_name:
        | dotted_name 'as' a=expression {
            RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use %s as import target", _PyPegen_get_expr_name(a)) }
    

    I haven't tested it extensively, so it might break something.

  5. sobolevn commented on Sep 3, 2024

    @sobolevn
    MemberAuthor

    Yes, this is the part I am working with. There are also cases of from a import (b as b1, c as c1), etc.

  6. lysnikolaou commented on Sep 3, 2024

    @lysnikolaou
    Member

    Right! You could do kind of the same approach in import_from_as_name for from imports I think.

  7. added a commit that references this issue on Sep 3, 2024
  8. added a commit that references this issue on Mar 13, 2025
  9. added a commit that references this issue on May 2, 2025
  10. added 3 commits that reference this issue on May 3, 2025
  11. added a commit that references this issue on May 3, 2025
  12. added 2 commits that reference this issue on Jul 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions