dissolve-python 0.3.0

A tool to dissolve deprecated calls in Python codebases
Documentation
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# dissolve

The dissolve library helps users replace calls to deprecated library APIs by
automatically substituting the deprecated function call with the body of the
deprecated function.

## Installation

Basic installation (for using the `@replace_me` decorator):

```console
$ pip install dissolve
```

This provides the `@replace_me` decorator for marking deprecated functions and generating
deprecation warnings with replacement suggestions.

For the `dissolve` command-line tool, first install the Python package:

```console
$ pip install dissolve
```

Then install the high-performance Rust binary:

```console
$ cargo install dissolve-python
```

If you don't have Rust installed:

```console
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
$ source ~/.cargo/env
$ cargo install dissolve-python
```

The Python package provides a wrapper that automatically detects and uses the Rust binary when available.

The CLI provides the following commands:
- `dissolve migrate`: Automatically replace deprecated function calls
- `dissolve cleanup`: Remove deprecated functions after migration
- `dissolve check`: Validate that deprecations can be migrated
- `dissolve info`: List all deprecated functions and their replacements

## Example

E.g. if you had a function "inc" that has been renamed to "increment" in
version 0.1.0 of your library:

```python
from dissolve import replace_me

def increment(x):
    return x + 1

@replace_me(since="0.1.0")
def inc(x):
    return increment(x)
```

Running this code will yield a warning:

```console
...
>>> inc(x=3)
<stdin>:1: DeprecationWarning: <function inc at 0x7feaf5ead5a0> has been deprecated since 0.1.0; use 'increment(x)' instead
4
```

Running the `dissolve migrate` command will automatically replace the
deprecated function call with the suggested replacement:

```console
$ dissolve migrate --write myproject/utils.py
Modified: myproject/utils.py
...
result = increment(x=3)
...
```

**For library users**: The migration step above is typically all you need.
Your code now uses the new `increment` function instead of the deprecated `inc` function.

**For library maintainers**: After users have had time to migrate and you're ready
to remove the deprecated function from your library, you can use `dissolve cleanup`:

```console
$ dissolve cleanup --all --write myproject/utils.py
Modified: myproject/utils.py
```

This removes the `inc` function entirely from the library, leaving only the `increment` function.

## dissolve migrate

The `dissolve migrate` command can automatically update your codebase to
replace deprecated function calls with their suggested replacements.

Usage:

```console
$ dissolve migrate path/to/code
```

This will:

1. Search for Python files in the specified path
2. Find calls to functions decorated with `@replace_me`
3. Replace them with the suggested replacement expression
4. Show a diff of the changes

Options:

* `-w, --write`: Write changes back to files instead of printing to stdout
* `--check`: Check if files need migration without modifying them (exits with code 1 if changes are needed)

Examples:

Preview changes:

```console
$ dissolve migrate myproject/utils.py
# Migrated: myproject/utils.py
...
result = 5 + 1
...
```

Check if migration is needed:

```console
$ dissolve migrate --check myproject/
myproject/utils.py: needs migration
myproject/core.py: up to date
$ echo $?
1
```

Apply changes:

```console
$ dissolve migrate --write myproject/
Modified: myproject/utils.py
Unchanged: myproject/core.py
```

The command respects the replacement expressions defined in the `@replace_me`
decorator and substitutes actual argument values.

## How dissolve Works

Dissolve uses type inference to determine which function calls to migrate. This
avoids false positives when different classes have methods with the same name.

### Type Tracking

When dissolve processes a file, it:

1. Tracks variable assignments to determine types
2. Follows imports to resolve fully qualified names
3. Scans imported modules for `@replace_me` decorated functions
4. Uses this information to match function calls to their definitions

For example:

```python
from mylib import OldClass
from other_lib import DifferentClass

obj1 = OldClass()
obj1.deprecated_method()  # Migrated - dissolve knows obj1 is OldClass

obj2 = DifferentClass()
obj2.deprecated_method()  # Not migrated - different class
```

### Import Resolution

Dissolve resolves imports to handle various import styles:

```python
# These imports of the same function:
from mylib.utils import old_function
from mylib.utils import old_function as legacy_func
import mylib.utils

# Are all recognized in these calls:
old_function()               # Direct import
legacy_func()                # Aliased import
mylib.utils.old_function()   # Module attribute access
```

### Context Managers

Variable assignments in `with` statements are tracked:

```python
with open_repo() as r:
    r.stage(files)  # dissolve tracks that r is the return type of open_repo()
```

### Inheritance

Method resolution includes parent classes:

```python
class Base:
    @replace_me()
    def old_method(self):
        return self.new_method()

class Child(Base):
    pass

obj = Child()
obj.old_method()  # Migrated even though method is defined in parent class
```

## dissolve cleanup

The `dissolve cleanup` command is designed for **library maintainers** to remove
deprecated functions from their codebase after a deprecation period has ended.
This command removes the entire function definition, not just the `@replace_me` 
decorator.

**Audience**: This command is primarily for library authors who want to clean up
their APIs after users have had time to migrate away from deprecated functions.

**Important**: This command removes the entire function definition, which will
break any code that still calls these functions. Only use this after:

1. Sufficient time has passed for users to migrate (based on your deprecation policy)
2. You've verified that usage of these functions has dropped to acceptable levels
3. You're prepared to release a new major version (if following semantic versioning)

Usage:

```console
$ dissolve cleanup [options] path/to/code
```

Options:

* `--all`: Remove all functions with `@replace_me` decorators regardless of version
* `--before VERSION`: Remove only functions with decorators older than the specified version
* `--current-version VERSION`: Remove functions marked with `remove_in` <= current version
* `-w, --write`: Write changes back to files (default: print to stdout)
* `--check`: Check if files have deprecated functions that can be removed without modifying them (exits with code 1 if changes are needed)

Examples:

Check if deprecated functions can be removed:

```console
$ dissolve cleanup --check --current-version 2.0.0 mylib/
mylib/utils.py: needs function cleanup
mylib/core.py: up to date
$ echo $?
1
```

Remove functions scheduled for removal in version 2.0.0:

```console
$ dissolve cleanup --current-version 2.0.0 --write mylib/
Modified: mylib/utils.py
Unchanged: mylib/core.py
```

Remove functions deprecated before version 2.0.0:

```console
$ dissolve cleanup --before 2.0.0 --write mylib/
```

This will remove functions like those decorated with `@replace_me(since="1.0.0")` 
but keep functions with `@replace_me(since="2.0.0")` and newer.

**Typical workflow for library maintainers:**

1. Add `@replace_me(since="X.Y.Z", remove_in="A.B.C")` to deprecated functions
2. Release version X.Y.Z with deprecation warnings
3. Wait for the planned removal version A.B.C
4. Run `dissolve cleanup --current-version A.B.C --write` to remove deprecated functions
5. Release version A.B.C as a new major version

## dissolve check

The `dissolve check` command verifies that all `@replace_me` decorated
functions in your codebase can be successfully processed by the `dissolve
migrate` command. This is useful for ensuring your deprecation decorators are
properly formatted.

Usage:

```console
$ dissolve check path/to/code
```

This will:

1. Search for Python files with `@replace_me` decorated functions
2. Verify that each decorated function has a valid replacement expression
3. Report any functions that cannot be processed by migrate

Examples:

Check all files in a directory:

```console
$ dissolve check myproject/
myproject/utils.py: 3 @replace_me function(s) can be replaced
myproject/core.py: 1 @replace_me function(s) can be replaced
```

When errors are found:

```console
$ dissolve check myproject/broken.py
myproject/broken.py: ERRORS found
  Function 'old_func' cannot be processed by migrate
```

The command exits with code 1 if any errors are found, making it useful in CI
pipelines to ensure all deprecations are properly formatted.

## Supported objects

The `replace_me` decorator can currently be applied to:

- Functions
- Async functions  
- Instance methods
- Class methods (`@classmethod`)
- Static methods (`@staticmethod`)
- Properties (`@property`)
- Classes
- Module and class attributes (using `replace_me(value)`)

### Class Deprecation

Classes can be deprecated by applying the `@replace_me` decorator to the class definition. The deprecated class should act as a wrapper around the new class, with the `__init__` method creating an instance of the replacement class:

```python
from dissolve import replace_me

class UserManager:
    def __init__(self, database_url, cache_size=100):
        self.db = Database(database_url)
        self.cache = Cache(cache_size)
    
    def get_user(self, user_id):
        return self.db.fetch_user(user_id)

@replace_me(since="2.0.0")
class UserService:
    def __init__(self, database_url, cache_size=50):
        self._manager = UserManager(database_url, cache_size * 2)
    
    def get_user(self, user_id):
        return self._manager.get_user(user_id)
    
    def old_method_name(self, arg):
        return self._manager.new_method_name(arg)
```

When the deprecated class is instantiated, this will emit a deprecation warning:

```console
>>> service = UserService("postgres://localhost", cache_size=25)
<stdin>:1: DeprecationWarning: <class UserService at 0x...> has been deprecated since 2.0.0; use 'UserManager("postgres://localhost", cache_size=25 * 2)' instead
```

The migration tool will replace all instantiations of the deprecated class with the wrapped class:

```console
$ dissolve migrate --write myproject.py
# UserService("config", cache_size=100) becomes:
# UserManager("config", cache_size=100 * 2)
```

Class deprecation works with all instantiation patterns including direct calls, list comprehensions, and factory patterns:

```python
# All of these will be migrated automatically:
service = UserService(db_url)
services = [UserService(url) for url in urls]
factory = lambda: UserService("default")
```

This approach allows library authors to provide full backward compatibility while guiding users to the new API. The deprecated class acts as a transparent wrapper that forwards method calls to the new implementation, and the migration tool automatically updates all usage sites to use the wrapped class directly.

Dissolve will automatically determine the appropriate replacement expression
based on the body of the decorated object. In some cases, this is not possible,
such as when the body is a complex expression or when the object is a lambda
function.

### Attribute Deprecation

Module-level constants and class attributes can be deprecated using `replace_me` as a function that wraps the value:

```python
from dissolve import replace_me

# Module-level attribute
OLD_API_URL = replace_me("https://api.example.com/v2")

# Class attribute
class Config:
    OLD_TIMEOUT = replace_me(30)
    OLD_DEBUG_MODE = replace_me(True)
```

When these attributes are used in code, the migration tool will replace them with the literal values:

```console
$ dissolve migrate --write myproject.py
# Before:
# url = OLD_API_URL
# timeout = Config.OLD_TIMEOUT

# After:
# url = "https://api.example.com/v2"
# timeout = 30
```

This is particularly useful for deprecating configuration constants that have been replaced by new values or moved to different locations. The `replace_me()` function call serves as a marker for the migration tool without adding any runtime overhead.

### Async Function Deprecation

Async functions are fully supported and work just like regular functions:

```python
from dissolve import replace_me
import asyncio

async def new_fetch_data(url, timeout=30):
    # Modern implementation
    return await fetch_with_timeout(url, timeout)

@replace_me(since="3.0.0")
async def old_fetch_data(url):
    return await new_fetch_data(url, timeout=30)
```

When called, this will emit:

```console
>>> await old_fetch_data("https://api.example.com")
<stdin>:1: DeprecationWarning: <function old_fetch_data at 0x...> has been deprecated since 3.0.0; use 'await new_fetch_data('https://api.example.com', timeout=30)' instead
```

The replacement expression correctly preserves the `await` keyword for async calls.

### Class Methods and Static Methods

Class methods and static methods are fully supported. The `@replace_me` decorator
can be combined with `@classmethod` and `@staticmethod` decorators:

```python
from dissolve import replace_me

class DataProcessor:
    @classmethod
    @replace_me(since="2.0.0")
    def old_process_data(cls, data):
        return cls.new_process_data(data.strip().upper())
    
    @classmethod
    def new_process_data(cls, processed_data):
        return f"Processed: {processed_data}"

    @staticmethod
    @replace_me(since="2.0.0")
    def old_utility_func(value):
        return new_utility_func(value * 10)
```

When called, these will emit appropriate deprecation warnings:

```console
>>> DataProcessor.old_process_data("  hello  ")
<stdin>:1: DeprecationWarning: <function DataProcessor.old_process_data at 0x...> has been deprecated since 2.0.0; use 'DataProcessor.new_process_data('  hello  '.strip().upper())' instead

>>> DataProcessor.old_utility_func(5)
<stdin>:1: DeprecationWarning: <function DataProcessor.old_utility_func at 0x...> has been deprecated since 2.0.0; use 'new_utility_func(5 * 10)' instead
```

The migration tool will correctly replace these calls:

```console
$ dissolve migrate --write myproject.py
# DataProcessor.old_process_data("test") becomes:
# DataProcessor.new_process_data("test".strip().upper())
```

## Optional Dependency Usage

If you don't want to add a runtime dependency on dissolve, you can define a
fallback implementation that mimics dissolve's basic deprecation warning
functionality:

```python
try:
    from dissolve import replace_me
except ModuleNotFoundError:
    import warnings

    def replace_me(since=None, remove_in=None):
        def decorator(func):
            def wrapper(*args, **kwargs):
                msg = f"{func.__name__} has been deprecated"
                if since:
                    msg += f" since {since}"
                if remove_in:
                    msg += f" and will be removed in {remove_in}"
                msg += ". Consider running 'dissolve migrate' to automatically update your code."
                warnings.warn(msg, DeprecationWarning, stacklevel=2)
                return func(*args, **kwargs)
            return wrapper
        return decorator
```

This fallback implementation provides the same decorator interface as
dissolve's `replace_me` decorator. When dissolve is installed, you get full
deprecation warnings with replacement suggestions and migration support. When
it's not installed, you still get basic deprecation warnings that include a
suggestion to use dissolve's migration tool.