File: README.md

package info (click to toggle)
importmagic 0.1.7-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,240 kB
  • sloc: python: 5,820; makefile: 6
file content (68 lines) | stat: -rw-r--r-- 1,932 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Import Magic [![image](https://secure.travis-ci.org/alecthomas/importmagic.png?branch=master)](https://travis-ci.org/alecthomas/importmagic)

The goal of this package is to be able to automatically manage imports in Python. To that end it can:

- Build an index of all known symbols in all packages.
- Find unresolved references in source, and resolve them against the index, effectively automating imports.
- Automatically arrange imports according to PEP8.

It was originally written for the Sublime Text 2 [Python Import Magic](https://github.com/alecthomas/SublimePythonImportMagic) plugin.

## Example of use in Sublime Text 2 plugin

![Example of Import Magic at work](importmagic.gif)


## Using the library

Build an index:

```python
index = importmagic.SymbolIndex()
index.build_index(sys.path)
with open('index.json') as fd:
    index.serialize(fd)
```

Load an existing index:

```python
with open('index.json') as fd:
    index = SymbolIndex.deserialize(fd)
```

Find unresolved and unreferenced symbols:

```python
scope = importmagic.Scope.from_source(python_source)
unresolved, unreferenced = scope.find_unresolved_and_unreferenced_symbols()
```

Print new import block:

```python
start_line, end_line, import_block = importmagic.get_update(python_source, index, unresolved, unreferenced)
```

Update source code with new import blocks:

```
python_source = importmagic.update_imports(python_source, index, unresolved, unreferenced)
```

For more fine-grained control over what symbols are imported, the index can be queried directly:

```python
imports = importmagic.Imports(index, python_source)
imports.remove(unreferenced)

for symbol in unresolved:
    for score, module, variable in index.symbol_scores(symbol):
        if variable is None:
            imports.add_import(module)
        else:
            imports.add_import_from(module, variable)
        break

python_source = imports.update_source()
```