pyflyby 1.10.4__cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. pyflyby/__init__.py +61 -0
  2. pyflyby/__main__.py +9 -0
  3. pyflyby/_autoimp.py +2228 -0
  4. pyflyby/_cmdline.py +591 -0
  5. pyflyby/_comms.py +221 -0
  6. pyflyby/_dbg.py +1383 -0
  7. pyflyby/_dynimp.py +154 -0
  8. pyflyby/_fast_iter_modules.cpython-312-x86_64-linux-gnu.so +0 -0
  9. pyflyby/_file.py +771 -0
  10. pyflyby/_flags.py +230 -0
  11. pyflyby/_format.py +186 -0
  12. pyflyby/_idents.py +227 -0
  13. pyflyby/_import_sorting.py +165 -0
  14. pyflyby/_importclns.py +658 -0
  15. pyflyby/_importdb.py +535 -0
  16. pyflyby/_imports2s.py +643 -0
  17. pyflyby/_importstmt.py +723 -0
  18. pyflyby/_interactive.py +2113 -0
  19. pyflyby/_livepatch.py +793 -0
  20. pyflyby/_log.py +107 -0
  21. pyflyby/_modules.py +646 -0
  22. pyflyby/_parse.py +1396 -0
  23. pyflyby/_py.py +2165 -0
  24. pyflyby/_saveframe.py +1145 -0
  25. pyflyby/_saveframe_reader.py +471 -0
  26. pyflyby/_util.py +458 -0
  27. pyflyby/_version.py +8 -0
  28. pyflyby/autoimport.py +20 -0
  29. pyflyby/etc/pyflyby/canonical.py +10 -0
  30. pyflyby/etc/pyflyby/common.py +27 -0
  31. pyflyby/etc/pyflyby/forget.py +10 -0
  32. pyflyby/etc/pyflyby/mandatory.py +10 -0
  33. pyflyby/etc/pyflyby/numpy.py +156 -0
  34. pyflyby/etc/pyflyby/std.py +335 -0
  35. pyflyby/importdb.py +19 -0
  36. pyflyby/libexec/pyflyby/colordiff +34 -0
  37. pyflyby/libexec/pyflyby/diff-colorize +148 -0
  38. pyflyby/share/emacs/site-lisp/pyflyby.el +112 -0
  39. pyflyby-1.10.4.data/scripts/collect-exports +76 -0
  40. pyflyby-1.10.4.data/scripts/collect-imports +58 -0
  41. pyflyby-1.10.4.data/scripts/find-import +38 -0
  42. pyflyby-1.10.4.data/scripts/prune-broken-imports +34 -0
  43. pyflyby-1.10.4.data/scripts/pyflyby-diff +34 -0
  44. pyflyby-1.10.4.data/scripts/reformat-imports +27 -0
  45. pyflyby-1.10.4.data/scripts/replace-star-imports +37 -0
  46. pyflyby-1.10.4.data/scripts/saveframe +299 -0
  47. pyflyby-1.10.4.data/scripts/tidy-imports +170 -0
  48. pyflyby-1.10.4.data/scripts/transform-imports +47 -0
  49. pyflyby-1.10.4.dist-info/METADATA +605 -0
  50. pyflyby-1.10.4.dist-info/RECORD +53 -0
  51. pyflyby-1.10.4.dist-info/WHEEL +6 -0
  52. pyflyby-1.10.4.dist-info/entry_points.txt +4 -0
  53. pyflyby-1.10.4.dist-info/licenses/LICENSE.txt +19 -0
pyflyby/_util.py ADDED
@@ -0,0 +1,458 @@
1
+ # pyflyby/_util.py.
2
+ # Copyright (C) 2011, 2012, 2013, 2014, 2015, 2018 Karl Chen.
3
+ # License: MIT http://opensource.org/licenses/MIT
4
+
5
+
6
+
7
+ from contextlib import contextmanager, ExitStack
8
+ import inspect
9
+ import os
10
+ import sys
11
+ import types
12
+
13
+ # There used to be a custom caching_attribute implementation
14
+ # this now uses functools's cached_property which is understood by
15
+ # various static analysis tools.
16
+ from functools import cached_property as cached_attribute # noqa: F401
17
+
18
+ # Python 2/3 compatibility
19
+ DictProxyType = type(object.__dict__)
20
+
21
+ if sys.version_info > (3,9):
22
+ from functools import cache as memoize
23
+ else:
24
+ def memoize(function):
25
+ cache = {}
26
+ def wrapped_fn(*args, **kwargs):
27
+ cache_key = (args, tuple(sorted(kwargs.items())))
28
+ try:
29
+ return cache[cache_key]
30
+ except KeyError:
31
+ result = function(*args, **kwargs)
32
+ cache[cache_key] = result
33
+ return result
34
+ wrapped_fn.cache = cache
35
+ return wrapped_fn
36
+
37
+
38
+ class WrappedAttributeError(Exception):
39
+ pass
40
+
41
+
42
+ def stable_unique(items):
43
+ """
44
+ Return a copy of ``items`` without duplicates. The order of other items is
45
+ unchanged.
46
+
47
+ >>> stable_unique([1,4,6,4,6,5,7])
48
+ [1, 4, 6, 5, 7]
49
+ """
50
+ result = []
51
+ seen = set()
52
+ for item in items:
53
+ if item in seen:
54
+ continue
55
+ seen.add(item)
56
+ result.append(item)
57
+ return result
58
+
59
+
60
+ def longest_common_prefix(items1, items2):
61
+ """
62
+ Return the longest common prefix.
63
+
64
+ >>> longest_common_prefix("abcde", "abcxy")
65
+ 'abc'
66
+
67
+ :rtype:
68
+ ``type(items1)``
69
+ """
70
+ n = 0
71
+ for x1, x2 in zip(items1, items2):
72
+ if x1 != x2:
73
+ break
74
+ n += 1
75
+ return items1[:n]
76
+
77
+
78
+ def prefixes(parts):
79
+ """
80
+ >>> list(prefixes("abcd"))
81
+ ['a', 'ab', 'abc', 'abcd']
82
+
83
+ """
84
+ for i in range(1, len(parts)+1):
85
+ yield parts[:i]
86
+
87
+
88
+ def indent(lines, prefix):
89
+ r"""
90
+ >>> indent('hello\nworld\n', '@@')
91
+ '@@hello\n@@world\n'
92
+ """
93
+ return "".join("%s%s\n"%(prefix,line) for line in lines.splitlines(False))
94
+
95
+
96
+ def partition(iterable, predicate):
97
+ """
98
+ >>> partition('12321233221', lambda c: int(c) % 2 == 0)
99
+ (['2', '2', '2', '2', '2'], ['1', '3', '1', '3', '3', '1'])
100
+
101
+ """
102
+ falses = []
103
+ trues = []
104
+ for item in iterable:
105
+ if predicate(item):
106
+ trues.append(item)
107
+ else:
108
+ falses.append(item)
109
+ return trues, falses
110
+
111
+
112
+ Inf = float('Inf')
113
+
114
+
115
+ @contextmanager
116
+ def NullCtx():
117
+ """
118
+ Context manager that does nothing.
119
+ """
120
+ yield
121
+
122
+
123
+ @contextmanager
124
+ def ImportPathCtx(path_additions):
125
+ """
126
+ Context manager that temporarily prepends ``sys.path`` with ``path_additions``.
127
+ """
128
+ if not isinstance(path_additions, (tuple, list)):
129
+ path_additions = [path_additions]
130
+ old_path = sys.path[:]
131
+ sys.path[0:0] = path_additions
132
+ try:
133
+ yield
134
+ finally:
135
+ sys.path[:] = old_path
136
+
137
+
138
+ @contextmanager
139
+ def CwdCtx(path):
140
+ """
141
+ Context manager that temporarily enters a new working directory.
142
+ """
143
+ old_cwd = os.getcwd()
144
+ os.chdir(str(path))
145
+ try:
146
+ yield
147
+ finally:
148
+ os.chdir(old_cwd)
149
+
150
+
151
+ @contextmanager
152
+ def EnvVarCtx(**kwargs):
153
+ """
154
+ Context manager that temporarily modifies os.environ.
155
+ """
156
+ unset = object()
157
+ old = {}
158
+ try:
159
+ for k, v in kwargs.items():
160
+ old[k] = os.environ.get(k, unset)
161
+ os.environ[k] = v
162
+ yield
163
+ finally:
164
+ for k, v in old.items():
165
+ if v is unset:
166
+ del os.environ[k]
167
+ else:
168
+ os.environ[k] = v
169
+
170
+
171
+ @contextmanager
172
+ def ExcludeImplicitCwdFromPathCtx():
173
+ """
174
+ Context manager that temporarily removes "." from ``sys.path``.
175
+ """
176
+ old_path = sys.path
177
+ try:
178
+ sys.path = [p for p in sys.path if p not in (".", "")]
179
+ yield
180
+ finally:
181
+ sys.path[:] = old_path
182
+
183
+
184
+ class FunctionWithGlobals(object):
185
+ """
186
+ A callable that at runtime adds extra variables to the target function's
187
+ global namespace.
188
+
189
+ This is written as a class with a __call__ method. We do so rather than
190
+ using a metafunction, so that we can also implement __getattr__ to look
191
+ through to the target.
192
+ """
193
+
194
+ def __init__(self, function, **variables):
195
+ self.__function = function
196
+ self.__variables = variables
197
+ try:
198
+ self.__original__ = variables["__original__"]
199
+ except KeyError:
200
+ pass
201
+
202
+ def __call__(self, *args, **kwargs):
203
+ function = self.__function
204
+ variables = self.__variables
205
+ undecorated = function
206
+ while True:
207
+ try:
208
+ undecorated = undecorated.undecorated
209
+ except AttributeError:
210
+ break
211
+ globals = undecorated.__globals__
212
+ UNSET = object()
213
+ old = {}
214
+ for k in variables:
215
+ old[k] = globals.get(k, UNSET)
216
+ try:
217
+ for k, v in variables.items():
218
+ globals[k] = v
219
+ return function(*args, **kwargs)
220
+ finally:
221
+ for k, v in old.items():
222
+ if v is UNSET:
223
+ del globals[k]
224
+ else:
225
+ globals[k] = v
226
+
227
+ def __getattr__(self, k):
228
+ return getattr(self.__original__, k)
229
+
230
+
231
+ def __get__(self, inst, cls=None):
232
+ if inst is None:
233
+ return self
234
+ return types.MethodType(self, inst)
235
+
236
+
237
+
238
+ class _WritableDictProxy(object):
239
+ """
240
+ Writable equivalent of cls.__dict__.
241
+ """
242
+
243
+ # We need to implement __getitem__ differently from __setitem__. The
244
+ # reason is because of an asymmetry in the mechanics of classes:
245
+ # - getattr(cls, k) does NOT in general do what we want because it
246
+ # returns unbound methods. It's actually equivalent to
247
+ # cls.__dict__[k].__get__(cls).
248
+ # - setattr(cls, k, v) does do what we want.
249
+ # - cls.__dict__[k] does do what we want.
250
+ # - cls.__dict__[k] = v does not work, because dictproxy is read-only.
251
+
252
+ def __init__(self, cls):
253
+ self._cls = cls
254
+
255
+ def __getitem__(self, k):
256
+ return self._cls.__dict__[k]
257
+
258
+ def get(self, k, default=None):
259
+ return self._cls.__dict__.get(k, default)
260
+
261
+ def __setitem__(self, k, v):
262
+ setattr(self._cls, k, v)
263
+
264
+ def __delitem__(self, k):
265
+ delattr(self._cls, k)
266
+
267
+
268
+ _UNSET = object()
269
+
270
+ class Aspect(object):
271
+ """
272
+ Monkey-patch a target method (joinpoint) with "around" advice.
273
+
274
+ The advice can call "__original__(...)". At run time, a global named
275
+ "__original__" will magically be available to the wrapped function.
276
+ This refers to the original function.
277
+
278
+ Suppose someone else wrote Foo.bar()::
279
+
280
+ >>> class Foo(object):
281
+ ... def __init__(self, x):
282
+ ... self.x = x
283
+ ... def bar(self, y):
284
+ ... return "bar(self.x=%s,y=%s)" % (self.x,y)
285
+
286
+ >>> foo = Foo(42)
287
+
288
+ To monkey patch ``foo.bar``, decorate the wrapper with ``"@advise(foo.bar)"``::
289
+
290
+ >>> @advise(foo.bar)
291
+ ... def addthousand(y):
292
+ ... return "advised foo.bar(y=%s): %s" % (y, __original__(y+1000))
293
+
294
+ >>> foo.bar(100)
295
+ 'advised foo.bar(y=100): bar(self.x=42,y=1100)'
296
+
297
+ You can uninstall the advice and get the original behavior back::
298
+
299
+ >>> addthousand.unadvise()
300
+
301
+ >>> foo.bar(100)
302
+ 'bar(self.x=42,y=100)'
303
+
304
+ :see:
305
+ http://en.wikipedia.org/wiki/Aspect-oriented_programming
306
+ """
307
+
308
+ _wrapper = None
309
+
310
+ def __init__(self, joinpoint):
311
+ spec = joinpoint
312
+ while hasattr(joinpoint, "__joinpoint__"):
313
+ joinpoint = joinpoint.__joinpoint__
314
+ self._joinpoint = joinpoint
315
+ if (isinstance(joinpoint, (types.FunctionType, type))
316
+ and not (joinpoint.__name__ != joinpoint.__qualname__)):
317
+ self._qname = "%s.%s" % (
318
+ joinpoint.__module__,
319
+ joinpoint.__name__)
320
+ self._container = sys.modules[joinpoint.__module__].__dict__
321
+ self._name = joinpoint.__name__
322
+ self._original = spec
323
+ assert spec == self._container[self._name], joinpoint
324
+ elif isinstance(joinpoint, types.MethodType) or (isinstance(joinpoint,
325
+ types.FunctionType) and joinpoint.__name__ !=
326
+ joinpoint.__qualname__) or isinstance(joinpoint, property):
327
+ if isinstance(joinpoint, property):
328
+ joinpoint = joinpoint.fget
329
+ self._wrapper = property
330
+ self._qname = '%s.%s' % (joinpoint.__module__,
331
+ joinpoint.__qualname__)
332
+ self._name = joinpoint.__name__
333
+ if getattr(joinpoint, '__self__', None) is None:
334
+ container_obj = getattr(inspect.getmodule(joinpoint),
335
+ joinpoint.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
336
+
337
+ self._container = _WritableDictProxy(container_obj)
338
+ self._original = spec
339
+ else:
340
+ # Instance method.
341
+ container_obj = joinpoint.__self__
342
+ self._container = container_obj.__dict__
343
+ self._original = spec
344
+ assert spec == getattr(container_obj, self._name), (container_obj, self._qname)
345
+ assert self._original == self._container.get(self._name, self._original)
346
+ elif isinstance(joinpoint, tuple) and len(joinpoint) == 2:
347
+ container, name = joinpoint
348
+ if isinstance(container, dict):
349
+ self._original = container[name]
350
+ self._container = container
351
+ self._qname = name
352
+ elif name in container.__dict__.get('_trait_values', ()):
353
+ # traitlet stuff from IPython
354
+ self._container = container._trait_values
355
+ self._original = self._container[name]
356
+ self._qname = name
357
+ elif isinstance(container.__dict__, DictProxyType):
358
+ original = getattr(container, name)
359
+ if hasattr(original, "__func__"):
360
+ # TODO: generalize this to work for all cases, not just classmethod
361
+ original = original.__func__
362
+ self._wrapper = classmethod
363
+ self._original = original
364
+ self._container = _WritableDictProxy(container)
365
+ self._qname = "%s.%s.%s" % (
366
+ container.__module__, container.__name__, name)
367
+ else:
368
+ # Keep track of the original. We use getattr on the
369
+ # container, instead of getitem on container.__dict__, so that
370
+ # it works even if it's a class dict proxy that inherits the
371
+ # value from a super class.
372
+ self._original = getattr(container, name)
373
+ self._container = container.__dict__
374
+ self._qname = "%s.%s.%s" % (
375
+ container.__class__.__module__,
376
+ container.__class__.__name__,
377
+ name)
378
+ self._name = name
379
+ # TODO: unbound method
380
+ else:
381
+ raise TypeError("JoinPoint: unexpected type %s"
382
+ % (type(joinpoint).__name__,))
383
+ self._wrapped = None
384
+
385
+ def advise(self, hook, once=False):
386
+ from pyflyby._log import logger
387
+ self._previous = self._container.get(self._name, _UNSET)
388
+ if once and getattr(self._previous, "__aspect__", None) :
389
+ # TODO: check that it's the same hook - at least check the name.
390
+ logger.debug("already advised %s", self._qname)
391
+ return None
392
+ logger.debug("advising %s", self._qname)
393
+ assert self._previous is _UNSET or self._previous == self._original
394
+ assert self._wrapped is None
395
+ # Create the wrapped function.
396
+ wrapped = FunctionWithGlobals(hook, __original__=self._original)
397
+ wrapped.__joinpoint__ = self._joinpoint
398
+ wrapped.__original__ = self._original
399
+ wrapped.__name__ = "%s__advised__%s" % (self._name, hook.__name__)
400
+ wrapped.__doc__ = "%s.\n\nAdvice %s:\n%s" % (
401
+ self._original.__doc__, hook.__name__, hook.__doc__)
402
+ wrapped.__aspect__ = self
403
+ if self._wrapper is not None:
404
+ wrapped = self._wrapper(wrapped)
405
+ self._wrapped = wrapped
406
+ # Install the wrapped function!
407
+ self._container[self._name] = wrapped
408
+ return self
409
+
410
+ def unadvise(self):
411
+ if self._wrapped is None:
412
+ return
413
+ cur = self._container.get(self._name, _UNSET)
414
+ if cur is self._wrapped:
415
+ from pyflyby._log import logger
416
+ logger.debug("unadvising %s", self._qname)
417
+ if self._previous is _UNSET:
418
+ del self._container[self._name]
419
+ else:
420
+ self._container[self._name] = self._previous
421
+ elif cur == self._previous:
422
+ pass
423
+ else:
424
+ from pyflyby._log import logger
425
+ logger.debug("%s seems modified; not unadvising it", self._name)
426
+ self._wrapped = None
427
+
428
+
429
+ def advise(joinpoint):
430
+ """
431
+ Advise ``joinpoint``.
432
+
433
+ See `Aspect`.
434
+ """
435
+ aspect = Aspect(joinpoint)
436
+ return aspect.advise
437
+
438
+
439
+ @contextmanager
440
+ def AdviceCtx(joinpoint, hook):
441
+ aspect = Aspect(joinpoint)
442
+ advice = aspect.advise(hook)
443
+ try:
444
+ yield
445
+ finally:
446
+ advice.unadvise()
447
+
448
+ # For Python 2/3 compatibility. cmp isn't included with six.
449
+ def cmp(a, b):
450
+ return (a > b) - (a < b)
451
+
452
+
453
+ # Create a context manager with an arbitrary number of contexts.
454
+ @contextmanager
455
+ def nested(*mgrs):
456
+ with ExitStack() as stack:
457
+ ctxes = [stack.enter_context(mgr) for mgr in mgrs]
458
+ yield ctxes
pyflyby/_version.py ADDED
@@ -0,0 +1,8 @@
1
+ # pyflyby/_version.py.
2
+
3
+ # License for THIS FILE ONLY: CC0 Public Domain Dedication
4
+ # http://creativecommons.org/publicdomain/zero/1.0/
5
+
6
+ import importlib.metadata
7
+
8
+ __version__ = importlib.metadata.version('pyflyby')
pyflyby/autoimport.py ADDED
@@ -0,0 +1,20 @@
1
+ # pyflyby/autoimport.py.
2
+ # Copyright (C) 2011, 2012, 2013, 2014 Karl Chen.
3
+ # License: MIT http://opensource.org/licenses/MIT
4
+
5
+ # Deprecated stub for backwards compatibility.
6
+ #
7
+ # Change your old code from:
8
+ # import pyflyby.autoimport
9
+ # pyflyby.autoimport.install_auto_importer()
10
+ # to:
11
+ # import pyflyby
12
+ # pyflyby.enable_auto_importer()
13
+
14
+
15
+
16
+ from pyflyby._interactive import enable_auto_importer
17
+
18
+ install_auto_importer = enable_auto_importer
19
+
20
+ __all__ = ['install_auto_importer']
@@ -0,0 +1,10 @@
1
+
2
+ # To make tidy-imports automatically transform imports, create a dictionary
3
+ # like this:
4
+ # __canonical_imports__ = {
5
+ # "oldmodule.oldname": "newmodule.newname"
6
+ # }
7
+ #
8
+ # You can write this in any *.py file in your $PYFLYBY_PATH,
9
+ # e.g. ~/.pyflyby/canonical.py.
10
+
@@ -0,0 +1,27 @@
1
+ from Crypto.Cipher import AES
2
+ import IPython
3
+ import blist
4
+ from blist import sorteddict
5
+ import cssutils
6
+ import dateutil
7
+ import dateutil.parser
8
+ import kerberos
9
+ import mutagen
10
+ import perl
11
+ import pexpect
12
+ import pstats
13
+ import pyflyby
14
+ from pyflyby import SaveframeReader, saveframe, xreload
15
+ import pylab
16
+ import pyodbc
17
+ import pysvn
18
+ import pytest
19
+ import pytz
20
+ import requests
21
+ import sqlalchemy
22
+ import sqlalchemy.orm
23
+ import sqlalchemy.sql
24
+ import sympy
25
+ import xlrd
26
+ import yaml
27
+ from yaml import MarkedYAMLError, YAMLError, YAMLObject
@@ -0,0 +1,10 @@
1
+ # To remove imports from the set of known imports, write, for example:
2
+ # __forget_imports__ = [
3
+ # 'numpy.sin',
4
+ # ]
5
+ #
6
+ # You can write this in any *.py file in your $PYFLYBY_PATH,
7
+ # e.g. ~/.pyflyby/forget.py.
8
+ #
9
+ # This can be useful if you're inheriting somebody else's import database.
10
+ # You can inherit most of the parent database, but exclude certain imports.
@@ -0,0 +1,10 @@
1
+ # The following __mandatory_imports__ line makes tidy-imports add the
2
+ # mentioned imports to all files.
3
+ # You can also include imports other than __future__ imports.
4
+ #
5
+ # You can write this in any *.py file in your $PYFLYBY_PATH,
6
+ # e.g. ~/.pyflyby/mandatory.py.
7
+
8
+ # __mandatory_imports__ = [
9
+ # 'from __future__ import absolute_import, division',
10
+ # ]