#import #pyimportparse

pyimportparse

A rust crate to parse python imports

6 releases

Uses new Rust 2024

new 0.2.3 May 3, 2025
0.2.2 May 3, 2025
0.2.0 Apr 29, 2025
0.1.1 Apr 17, 2025

#1340 in Parser implementations

Download history 273/week @ 2025-04-15 22/week @ 2025-04-22 521/week @ 2025-04-29

816 downloads per month

MIT license

25KB
684 lines

pyimportparse

A rust crate to parse python imports (while ignoring the rest of the code).

Motivation:

Use with care. I've run the parser over the Django codebase and the results suggest that all imports were successfully parsed. However, there could still be cases where the parser does not behave correctly.

use pyimportparse::{parse_imports, Import};

let code = r#"
import a
from b import c
from .d import (e, f)
from ..g import *

if TYPE_CHECKING:
    import h

def foo():
    import i
"#;
    
let imports = parse_imports(&code).unwrap();
    
assert_eq!(vec![
    // (imported_object, line_number, typechecking_only)
    Import::new("a".to_owned(), 2, false),
    Import::new("b.c".to_owned(), 3, false),
    Import::new(".d.e".to_owned(), 4, false),
    Import::new(".d.f".to_owned(), 4, false),
    Import::new("..g.*".to_owned(), 5, false),
    Import::new("h".to_owned(), 8, true),
    Import::new("i".to_owned(), 11, false),
], imports);




Dependencies

~3–4MB
~73K SLoC