index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
|---|---|---|---|---|---|
706,543
|
pandas_ta.overlap.zlma
|
zlma
|
Zero Lag Moving Average (ZLMA)
The Zero Lag Moving Average attempts to eliminate the lag associated
with moving averages. This is an adaption created by John Ehler and Ric Way.
Sources:
https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average
Calculation:
Default Inputs:
length=10, mamode=EMA
EMA = Exponential Moving Average
lag = int(0.5 * (length - 1))
SOURCE = 2 * close - close.shift(lag)
ZLMA = MA(kind=mamode, SOURCE, length)
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
mamode (str): Options: 'ema', 'hma', 'sma', 'wma'. Default: 'ema'
offset (int): How many periods to offset the result. Default: 0
Kwargs:
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
Returns:
pd.Series: New feature generated.
|
def zlma(close, length=None, mamode=None, offset=None, **kwargs):
"""Indicator: Zero Lag Moving Average (ZLMA)"""
# Validate Arguments
length = int(length) if length and length > 0 else 10
mamode = mamode.lower() if isinstance(mamode, str) else "ema"
close = verify_series(close, length)
offset = get_offset(offset)
if close is None: return
# Calculate Result
lag = int(0.5 * (length - 1))
close_ = 2 * close - close.shift(lag)
if mamode == "dema": zlma = dema(close_, length=length, **kwargs)
elif mamode == "hma": zlma = hma(close_, length=length, **kwargs)
elif mamode == "linreg": zlma = linreg(close_, length=length, **kwargs)
elif mamode == "rma": zlma = rma(close_, length=length, **kwargs)
elif mamode == "sma": zlma = sma(close_, length=length, **kwargs)
elif mamode == "swma": zlma = swma(close_, length=length, **kwargs)
elif mamode == "t3": zlma = t3(close_, length=length, **kwargs)
elif mamode == "tema": zlma = tema(close_, length=length, **kwargs)
elif mamode == "trima": zlma = trima(close_, length=length, **kwargs)
elif mamode == "vidya": zlma = vidya(close_, length=length, **kwargs)
elif mamode == "wma": zlma = wma(close_, length=length, **kwargs)
else: zlma = ema(close_, length=length, **kwargs) # "ema"
# Offset
if offset != 0:
zlma = zlma.shift(offset)
# Handle fills
if "fillna" in kwargs:
zlma.fillna(kwargs["fillna"], inplace=True)
if "fill_method" in kwargs:
zlma.fillna(method=kwargs["fill_method"], inplace=True)
# Name & Category
zlma.name = f"ZL_{zlma.name}"
zlma.category = "overlap"
return zlma
|
(close, length=None, mamode=None, offset=None, **kwargs)
|
706,544
|
pandas_ta.statistics.zscore
|
zscore
|
Rolling Z Score
Sources:
Calculation:
Default Inputs:
length=30, std=1
SMA = Simple Moving Average
STDEV = Standard Deviation
std = std * STDEV(close, length)
mean = SMA(close, length)
ZSCORE = (close - mean) / std
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 30
std (float): It's period. Default: 1
offset (int): How many periods to offset the result. Default: 0
Kwargs:
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
Returns:
pd.Series: New feature generated.
|
def zscore(close, length=None, std=None, offset=None, **kwargs):
"""Indicator: Z Score"""
# Validate Arguments
length = int(length) if length and length > 1 else 30
std = float(std) if std and std > 1 else 1
close = verify_series(close, length)
offset = get_offset(offset)
if close is None: return
# Calculate Result
std *= stdev(close=close, length=length, **kwargs)
mean = sma(close=close, length=length, **kwargs)
zscore = (close - mean) / std
# Offset
if offset != 0:
zscore = zscore.shift(offset)
# Handle fills
if "fillna" in kwargs:
zscore.fillna(kwargs["fillna"], inplace=True)
if "fill_method" in kwargs:
zscore.fillna(method=kwargs["fill_method"], inplace=True)
# Name & Category
zscore.name = f"ZS_{length}"
zscore.category = "statistics"
return zscore
|
(close, length=None, std=None, offset=None, **kwargs)
|
706,545
|
pycmx.edit
|
Edit
|
An individual source-to-record operation, with a source roll, source and
recorder timecode in and out, a transition and channels.
|
class Edit:
"""
An individual source-to-record operation, with a source roll, source and
recorder timecode in and out, a transition and channels.
"""
def __init__(self, edit_statement, audio_ext_statement, clip_name_statement, source_file_statement, trans_name_statement = None):
self.edit_statement = edit_statement
self.audio_ext = audio_ext_statement
self.clip_name_statement = clip_name_statement
self.source_file_statement = source_file_statement
self.trans_name_statement = trans_name_statement
@property
def line_number(self) -> int:
"""
Get the line number for the "standard form" statement associated with
this edit. Line numbers a zero-indexed, such that the
"TITLE:" record is line zero.
"""
return self.edit_statement.line_number
@property
def channels(self) -> ChannelMap:
"""
Get the :obj:`ChannelMap` object associated with this Edit.
"""
cm = ChannelMap()
cm._append_event(self.edit_statement.channels)
if self.audio_ext != None:
cm._append_ext(self.audio_ext)
return cm
@property
def transition(self) -> Transition:
"""
Get the :obj:`Transition` object associated with this edit.
"""
if self.trans_name_statement:
return Transition(self.edit_statement.trans, self.edit_statement.trans_op, self.trans_name_statement.name)
else:
return Transition(self.edit_statement.trans, self.edit_statement.trans_op, None)
@property
def source_in(self) -> str:
"""
Get the source in timecode.
"""
return self.edit_statement.source_in
@property
def source_out(self) -> str:
"""
Get the source out timecode.
"""
return self.edit_statement.source_out
@property
def record_in(self) -> str:
"""
Get the record in timecode.
"""
return self.edit_statement.record_in
@property
def record_out(self) -> str:
"""
Get the record out timecode.
"""
return self.edit_statement.record_out
@property
def source(self) -> str:
"""
Get the source column. This is the 8, 32 or 128-character string on the
event record line, this usually references the tape name of the source.
"""
return self.edit_statement.source
@property
def black(self) -> bool:
"""
Black video or silence should be used as the source for this event.
"""
return self.source == "BL"
@property
def aux_source(self) -> bool:
"""
An auxiliary source is the source of this event.
"""
return self.source == "AX"
@property
def source_file(self) -> Optional[str]:
"""
Get the source file, as attested by a "* SOURCE FILE" remark on the
EDL. This will return None if the information is not present.
"""
if self.source_file_statement is None:
return None
else:
return self.source_file_statement.filename
@property
def clip_name(self) -> Optional[str]:
"""
Get the clip name, as attested by a "* FROM CLIP NAME" or "* TO CLIP
NAME" remark on the EDL. This will return None if the information is
not present.
"""
if self.clip_name_statement is None:
return None
else:
return self.clip_name_statement.name
|
(edit_statement, audio_ext_statement, clip_name_statement, source_file_statement, trans_name_statement=None)
|
706,546
|
pycmx.edit
|
__init__
| null |
def __init__(self, edit_statement, audio_ext_statement, clip_name_statement, source_file_statement, trans_name_statement = None):
self.edit_statement = edit_statement
self.audio_ext = audio_ext_statement
self.clip_name_statement = clip_name_statement
self.source_file_statement = source_file_statement
self.trans_name_statement = trans_name_statement
|
(self, edit_statement, audio_ext_statement, clip_name_statement, source_file_statement, trans_name_statement=None)
|
706,547
|
pycmx.event
|
Event
|
Represents a collection of :class:`~pycmx.edit.Edit` s, all with the same event number.
|
class Event:
"""
Represents a collection of :class:`~pycmx.edit.Edit` s, all with the same event number.
"""
def __init__(self, statements):
self.statements = statements
@property
def number(self) -> int:
"""
Return the event number.
"""
return int(self._edit_statements()[0].event)
@property
def edits(self) -> List[Edit]:
"""
Returns the edits. Most events will have a single edit, a single event
will have multiple edits when a dissolve, wipe or key transition needs
to be performed.
"""
edits_audio = list( self._statements_with_audio_ext() )
clip_names = self._clip_name_statements()
source_files= self._source_file_statements()
the_zip: List[List[Any]] = [edits_audio]
if len(edits_audio) == 2:
start_name: Optional[StmtClipName] = None
end_name: Optional[StmtClipName] = None
for clip_name in clip_names:
if clip_name.affect == 'from':
start_name = clip_name
elif clip_name.affect == 'to':
end_name = clip_name
the_zip.append([start_name, end_name])
else:
if len(edits_audio) == len(clip_names):
the_zip.append(clip_names)
else:
the_zip.append([None] * len(edits_audio) )
if len(edits_audio) == len(source_files):
the_zip.append(source_files)
elif len(source_files) == 1:
the_zip.append( source_files * len(edits_audio) )
else:
the_zip.append([None] * len(edits_audio) )
# attach trans name to last event
try:
trans_statement = self._trans_name_statements()[0]
trans_names: List[Optional[Any]] = [None] * (len(edits_audio) - 1)
trans_names.append(trans_statement)
the_zip.append(trans_names)
except IndexError:
the_zip.append([None] * len(edits_audio) )
return [ Edit(edit_statement=e1[0],
audio_ext_statement=e1[1],
clip_name_statement=n1,
source_file_statement=s1,
trans_name_statement=u1) for (e1,n1,s1,u1) in zip(*the_zip) ]
@property
def unrecognized_statements(self) -> Generator[StmtUnrecognized, None, None]:
"""
A generator for all the unrecognized statements in the event.
"""
for s in self.statements:
if type(s) is StmtUnrecognized:
yield s
def _trans_name_statements(self) -> List[StmtEffectsName]:
return [s for s in self.statements if type(s) is StmtEffectsName]
def _edit_statements(self) -> List[StmtEvent]:
return [s for s in self.statements if type(s) is StmtEvent]
def _clip_name_statements(self) -> List[StmtClipName]:
return [s for s in self.statements if type(s) is StmtClipName]
def _source_file_statements(self) -> List[StmtSourceFile]:
return [s for s in self.statements if type(s) is StmtSourceFile]
def _statements_with_audio_ext(self) -> Generator[Tuple[StmtEvent, Optional[StmtAudioExt]], None, None]:
for (s1, s2) in zip(self.statements, self.statements[1:]):
if type(s1) is StmtEvent and type(s2) is StmtAudioExt:
yield (s1,s2)
elif type(s1) is StmtEvent:
yield (s1, None)
|
(statements)
|
706,548
|
pycmx.event
|
__init__
| null |
def __init__(self, statements):
self.statements = statements
|
(self, statements)
|
706,549
|
pycmx.event
|
_clip_name_statements
| null |
def _clip_name_statements(self) -> List[StmtClipName]:
return [s for s in self.statements if type(s) is StmtClipName]
|
(self) -> List[pycmx.parse_cmx_statements.ClipName]
|
706,550
|
pycmx.event
|
_edit_statements
| null |
def _edit_statements(self) -> List[StmtEvent]:
return [s for s in self.statements if type(s) is StmtEvent]
|
(self) -> List[pycmx.parse_cmx_statements.Event]
|
706,551
|
pycmx.event
|
_source_file_statements
| null |
def _source_file_statements(self) -> List[StmtSourceFile]:
return [s for s in self.statements if type(s) is StmtSourceFile]
|
(self) -> List[pycmx.parse_cmx_statements.SourceFile]
|
706,552
|
pycmx.event
|
_statements_with_audio_ext
| null |
def _statements_with_audio_ext(self) -> Generator[Tuple[StmtEvent, Optional[StmtAudioExt]], None, None]:
for (s1, s2) in zip(self.statements, self.statements[1:]):
if type(s1) is StmtEvent and type(s2) is StmtAudioExt:
yield (s1,s2)
elif type(s1) is StmtEvent:
yield (s1, None)
|
(self) -> Generator[Tuple[pycmx.parse_cmx_statements.Event, Optional[pycmx.parse_cmx_statements.AudioExt]], NoneType, NoneType]
|
706,553
|
pycmx.event
|
_trans_name_statements
| null |
def _trans_name_statements(self) -> List[StmtEffectsName]:
return [s for s in self.statements if type(s) is StmtEffectsName]
|
(self) -> List[pycmx.parse_cmx_statements.EffectsName]
|
706,554
|
pycmx.transition
|
Transition
|
A CMX transition: a wipe, dissolve or cut.
|
class Transition:
"""
A CMX transition: a wipe, dissolve or cut.
"""
Cut = "C"
Dissolve = "D"
Wipe = "W"
KeyBackground = "KB"
Key = "K"
KeyOut = "KO"
def __init__(self, transition, operand, name=None):
self.transition = transition
self.operand = operand
self.name = name
@property
def kind(self) -> Optional[str]:
"""
Return the kind of transition: Cut, Wipe, etc
"""
if self.cut:
return Transition.Cut
elif self.dissolve:
return Transition.Dissolve
elif self.wipe:
return Transition.Wipe
elif self.key_background:
return Transition.KeyBackground
elif self.key_foreground:
return Transition.Key
elif self.key_out:
return Transition.KeyOut
@property
def cut(self) -> bool:
"`True` if this transition is a cut."
return self.transition == 'C'
@property
def dissolve(self) -> bool:
"`True` if this traansition is a dissolve."
return self.transition == 'D'
@property
def wipe(self) -> bool:
"`True` if this transition is a wipe."
return self.transition.startswith('W')
@property
def effect_duration(self) -> int:
"""The duration of this transition, in frames of the record target.
In the event of a key event, this is the duration of the fade in.
"""
return int(self.operand)
@property
def wipe_number(self) -> Optional[int]:
"Wipes are identified by a particular number."
if self.wipe:
return int(self.transition[1:])
else:
return None
@property
def key_background(self) -> bool:
"`True` if this edit is a key background."
return self.transition == Transition.KeyBackground
@property
def key_foreground(self) -> bool:
"`True` if this edit is a key foreground."
return self.transition == Transition.Key
@property
def key_out(self) -> bool:
"""
`True` if this edit is a key out. This material will removed from
the key foreground and replaced with the key background.
"""
return self.transition == Transition.KeyOut
|
(transition, operand, name=None)
|
706,555
|
pycmx.transition
|
__init__
| null |
def __init__(self, transition, operand, name=None):
self.transition = transition
self.operand = operand
self.name = name
|
(self, transition, operand, name=None)
|
706,560
|
pycmx.parse_cmx_events
|
parse_cmx3600
|
Parse a CMX 3600 EDL.
:param TextIO f: a file-like object, anything that's readlines-able.
:returns: An :class:`pycmx.edit_list.EditList`.
|
def parse_cmx3600(f: TextIO):
"""
Parse a CMX 3600 EDL.
:param TextIO f: a file-like object, anything that's readlines-able.
:returns: An :class:`pycmx.edit_list.EditList`.
"""
statements = parse_cmx3600_statements(f)
return EditList(statements)
|
(f: <class 'TextIO'>)
|
706,587
|
pytest_testconfig
|
load_ini
|
Parse and collapse a ConfigParser-Style ini file into a two-level
config structure.
|
def load_ini(ini_file, encoding):
""" Parse and collapse a ConfigParser-Style ini file into a two-level
config structure. """
global config
tmpconfig = ConfigParser.ConfigParser()
# Overriding optionxform method to avoid lowercase conversion
tmpconfig.optionxform = lambda override: override
with codecs.open(os.path.expanduser(ini_file), 'r', encoding) as f:
try:
tmpconfig.read_file(f)
except AttributeError:
tmpconfig.readfp(f)
parsed_config = {}
for section in tmpconfig.sections():
parsed_config[section] = {}
for option in tmpconfig.options(section):
parsed_config[section][option] = tmpconfig.get(section, option)
merge_map(config, parsed_config)
|
(ini_file, encoding)
|
706,588
|
pytest_testconfig
|
load_json
|
This will use the json module to to read in the config json file.
|
def load_json(json_file, encoding):
""" This will use the json module to to read in the config json file.
"""
import json
global config
with codecs.open(os.path.expanduser(json_file), 'r', encoding) as f:
parsed_config = json.load(f)
merge_map(config, parsed_config)
|
(json_file, encoding)
|
706,589
|
pytest_testconfig
|
load_python
|
This will exec the defined python file into the config variable -
the implicit assumption is that the python is safe, well formed and will
not do anything bad. This is also dangerous.
|
def load_python(py_file, encoding):
""" This will exec the defined python file into the config variable -
the implicit assumption is that the python is safe, well formed and will
not do anything bad. This is also dangerous. """
with codecs.open(os.path.expanduser(py_file), 'r', encoding) as f:
exec(f.read())
|
(py_file, encoding)
|
706,590
|
pytest_testconfig
|
load_yaml
|
Load the passed in yaml configuration file
|
def load_yaml(yaml_file, encoding):
""" Load the passed in yaml configuration file """
try:
import yaml
except (ImportError):
raise Exception('unable to import YAML package. Can not continue.')
global config
with codecs.open(os.path.expanduser(yaml_file), 'r', encoding) as f:
parsed_config = yaml.safe_load(f.read())
merge_map(config, parsed_config)
|
(yaml_file, encoding)
|
706,592
|
pytest_testconfig
|
merge_map
|
Merges a new map of configuration recursively with an older one
|
def merge_map(original, to_add):
""" Merges a new map of configuration recursively with an older one """
for k, v in to_add.items():
if isinstance(v, dict) and k in original and isinstance(original[k],
dict):
merge_map(original[k], v)
else:
original[k] = v
|
(original, to_add)
|
706,594
|
pytest_testconfig
|
pytest_addoption
|
Define the command line options for the plugin.
|
def pytest_addoption(parser, env=os.environ):
""" Define the command line options for the plugin. """
group = parser.getgroup('test-config')
group.addoption('--tc-file',
action='append',
dest='testconfig',
default=[env.get(env_opt)],
help="Configuration file to parse and pass to tests"
" [PY_TEST_CONFIG_FILE]")
group.addoption('--tc-file-encoding',
action='store',
dest='testconfigencoding',
default=env.get('PY_TEST_CONFIG_FILE_ENCODING') or encoding_option,
help="Test config file encoding, default is utf-8"
" [PY_TEST_CONFIG_FILE_ENCODING]")
group.addoption('--tc-format',
action='store',
dest='testconfigformat',
default=env.get('PY_TEST_CONFIG_FILE_FORMAT') or format_option,
help="Test config file format, default is configparser ini format"
" [PY_TEST_CONFIG_FILE_FORMAT]")
group.addoption('--tc',
action='append',
dest='overrides',
default=[],
help="Option:Value specific overrides.")
group.addoption('--tc-exact',
action='store_true',
dest='exact',
default=False,
help="Optional: Do not explode periods in override keys to "
"individual keys within the config dict, instead treat them"
" as config[my.toplevel.key] ala sqlalchemy.url in pylons")
# Add github marker to --help
parser.addini("github", "GitHub issue integration", "args")
|
(parser, env=environ({'PATH': '/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'HOSTNAME': '2aea7552519e', 'LANG': 'C.UTF-8', 'GPG_KEY': 'A035C8C19219BA821ECEA86B64E628F8D684696D', 'PYTHON_VERSION': '3.10.14', 'PYTHON_PIP_VERSION': '23.0.1', 'PYTHON_SETUPTOOLS_VERSION': '65.5.1', 'PYTHON_GET_PIP_URL': 'https://github.com/pypa/get-pip/raw/dbf0c85f76fb6e1ab42aa672ffca6f0a675d9ee4/public/get-pip.py', 'PYTHON_GET_PIP_SHA256': 'dfe9fd5c28dc98b5ac17979a953ea550cec37ae1b47a5116007395bfacff2ab9', 'HOME': '/root', 'VIRTUAL_ENV': '/usr/local'}))
|
706,595
|
pytest_testconfig
|
pytest_cmdline_main
|
Call the super and then validate and call the relevant parser for
the configuration file passed in
|
def pytest_cmdline_main(config):
""" Call the super and then validate and call the relevant parser for
the configuration file passed in """
global py_config
if not config.getoption('testconfig') and not config.getoption('overrides'):
return
if config.getoption('testconfigformat'):
format_option = config.getoption('testconfigformat')
if format_option not in valid_loaders.keys():
raise Exception('%s is not a valid configuration file format' \
% format_option)
# Load the configuration file:
for configfile in config.getoption('testconfig'):
if configfile:
valid_loaders[format_option](configfile,
config.getoption('testconfigencoding'))
overrides = tolist(config.getoption('overrides')) or []
for override in overrides:
keys, val = override.split(":", 1)
if config.getoption('exact'):
py_config[keys] = val
else:
# Create all *parent* keys that may not exist in the config
section = py_config
keys = keys.split('.')
for key in keys[:-1]:
if key not in section:
section[key] = {}
section = section[key]
# Finally assign the value to the last key
key = keys[-1]
section[key] = val
|
(config)
|
706,597
|
pytest_testconfig
|
tolist
|
Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
|
def tolist(val):
"""Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
"""
if val is None:
return None
try:
# might already be a list
val.extend([])
return val
except AttributeError:
pass
# might be a string
try:
return re.split(r'\s*,\s*', val)
except TypeError:
# who knows...
return list(val)
|
(val)
|
706,598
|
remote_pdb
|
LF2CRLF_FileWrapper
| null |
class LF2CRLF_FileWrapper(object):
def __init__(self, connection):
self.connection = connection
self.stream = fh = connection.makefile('rw')
self.read = fh.read
self.readline = fh.readline
self.readlines = fh.readlines
self.close = fh.close
self.flush = fh.flush
self.fileno = fh.fileno
if hasattr(fh, 'encoding'):
self._send = lambda data: connection.sendall(data.encode(fh.encoding))
else:
self._send = connection.sendall
@property
def encoding(self):
return self.stream.encoding
def __iter__(self):
return self.stream.__iter__()
def write(self, data, nl_rex=re.compile("\r?\n")):
data = nl_rex.sub("\r\n", data)
self._send(data)
def writelines(self, lines, nl_rex=re.compile("\r?\n")):
for line in lines:
self.write(line, nl_rex)
|
(connection)
|
706,599
|
remote_pdb
|
__init__
| null |
def __init__(self, connection):
self.connection = connection
self.stream = fh = connection.makefile('rw')
self.read = fh.read
self.readline = fh.readline
self.readlines = fh.readlines
self.close = fh.close
self.flush = fh.flush
self.fileno = fh.fileno
if hasattr(fh, 'encoding'):
self._send = lambda data: connection.sendall(data.encode(fh.encoding))
else:
self._send = connection.sendall
|
(self, connection)
|
706,600
|
remote_pdb
|
__iter__
| null |
def __iter__(self):
return self.stream.__iter__()
|
(self)
|
706,601
|
remote_pdb
|
write
| null |
def write(self, data, nl_rex=re.compile("\r?\n")):
data = nl_rex.sub("\r\n", data)
self._send(data)
|
(self, data, nl_rex=re.compile('\r?\n'))
|
706,602
|
remote_pdb
|
writelines
| null |
def writelines(self, lines, nl_rex=re.compile("\r?\n")):
for line in lines:
self.write(line, nl_rex)
|
(self, lines, nl_rex=re.compile('\r?\n'))
|
706,603
|
pdb
|
Pdb
| null |
class Pdb(bdb.Bdb, cmd.Cmd):
_previous_sigint_handler = None
def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
nosigint=False, readrc=True):
bdb.Bdb.__init__(self, skip=skip)
cmd.Cmd.__init__(self, completekey, stdin, stdout)
sys.audit("pdb.Pdb")
if stdout:
self.use_rawinput = 0
self.prompt = '(Pdb) '
self.aliases = {}
self.displaying = {}
self.mainpyfile = ''
self._wait_for_mainpyfile = False
self.tb_lineno = {}
# Try to load readline if it exists
try:
import readline
# remove some common file name delimiters
readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
except ImportError:
pass
self.allow_kbdint = False
self.nosigint = nosigint
# Read ~/.pdbrc and ./.pdbrc
self.rcLines = []
if readrc:
try:
with open(os.path.expanduser('~/.pdbrc')) as rcFile:
self.rcLines.extend(rcFile)
except OSError:
pass
try:
with open(".pdbrc") as rcFile:
self.rcLines.extend(rcFile)
except OSError:
pass
self.commands = {} # associates a command list to breakpoint numbers
self.commands_doprompt = {} # for each bp num, tells if the prompt
# must be disp. after execing the cmd list
self.commands_silent = {} # for each bp num, tells if the stack trace
# must be disp. after execing the cmd list
self.commands_defining = False # True while in the process of defining
# a command list
self.commands_bnum = None # The breakpoint number for which we are
# defining a list
def sigint_handler(self, signum, frame):
if self.allow_kbdint:
raise KeyboardInterrupt
self.message("\nProgram interrupted. (Use 'cont' to resume).")
self.set_step()
self.set_trace(frame)
def reset(self):
bdb.Bdb.reset(self)
self.forget()
def forget(self):
self.lineno = None
self.stack = []
self.curindex = 0
self.curframe = None
self.tb_lineno.clear()
def setup(self, f, tb):
self.forget()
self.stack, self.curindex = self.get_stack(f, tb)
while tb:
# when setting up post-mortem debugging with a traceback, save all
# the original line numbers to be displayed along the current line
# numbers (which can be different, e.g. due to finally clauses)
lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
self.tb_lineno[tb.tb_frame] = lineno
tb = tb.tb_next
self.curframe = self.stack[self.curindex][0]
# The f_locals dictionary is updated from the actual frame
# locals whenever the .f_locals accessor is called, so we
# cache it here to ensure that modifications are not overwritten.
self.curframe_locals = self.curframe.f_locals
return self.execRcLines()
# Can be executed earlier than 'setup' if desired
def execRcLines(self):
if not self.rcLines:
return
# local copy because of recursion
rcLines = self.rcLines
rcLines.reverse()
# execute every line only once
self.rcLines = []
while rcLines:
line = rcLines.pop().strip()
if line and line[0] != '#':
if self.onecmd(line):
# if onecmd returns True, the command wants to exit
# from the interaction, save leftover rc lines
# to execute before next interaction
self.rcLines += reversed(rcLines)
return True
# Override Bdb methods
def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self._wait_for_mainpyfile:
return
if self.stop_here(frame):
self.message('--Call--')
self.interaction(frame, None)
def user_line(self, frame):
"""This function is called when we stop or break at this line."""
if self._wait_for_mainpyfile:
if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
or frame.f_lineno <= 0):
return
self._wait_for_mainpyfile = False
if self.bp_commands(frame):
self.interaction(frame, None)
def bp_commands(self, frame):
"""Call every command that was set for the current active breakpoint
(if there is one).
Returns True if the normal interaction function must be called,
False otherwise."""
# self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
if getattr(self, "currentbp", False) and \
self.currentbp in self.commands:
currentbp = self.currentbp
self.currentbp = 0
lastcmd_back = self.lastcmd
self.setup(frame, None)
for line in self.commands[currentbp]:
self.onecmd(line)
self.lastcmd = lastcmd_back
if not self.commands_silent[currentbp]:
self.print_stack_entry(self.stack[self.curindex])
if self.commands_doprompt[currentbp]:
self._cmdloop()
self.forget()
return
return 1
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
if self._wait_for_mainpyfile:
return
frame.f_locals['__return__'] = return_value
self.message('--Return--')
self.interaction(frame, None)
def user_exception(self, frame, exc_info):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
if self._wait_for_mainpyfile:
return
exc_type, exc_value, exc_traceback = exc_info
frame.f_locals['__exception__'] = exc_type, exc_value
# An 'Internal StopIteration' exception is an exception debug event
# issued by the interpreter when handling a subgenerator run with
# 'yield from' or a generator controlled by a for loop. No exception has
# actually occurred in this case. The debugger uses this debug event to
# stop when the debuggee is returning from such generators.
prefix = 'Internal ' if (not exc_traceback
and exc_type is StopIteration) else ''
self.message('%s%s' % (prefix,
traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
self.interaction(frame, exc_traceback)
# General interaction function
def _cmdloop(self):
while True:
try:
# keyboard interrupts allow for an easy way to cancel
# the current command, so allow them during interactive input
self.allow_kbdint = True
self.cmdloop()
self.allow_kbdint = False
break
except KeyboardInterrupt:
self.message('--KeyboardInterrupt--')
# Called before loop, handles display expressions
def preloop(self):
displaying = self.displaying.get(self.curframe)
if displaying:
for expr, oldvalue in displaying.items():
newvalue = self._getval_except(expr)
# check for identity first; this prevents custom __eq__ to
# be called at every loop, and also prevents instances whose
# fields are changed to be displayed
if newvalue is not oldvalue and newvalue != oldvalue:
displaying[expr] = newvalue
self.message('display %s: %r [old: %r]' %
(expr, newvalue, oldvalue))
def interaction(self, frame, traceback):
# Restore the previous signal handler at the Pdb prompt.
if Pdb._previous_sigint_handler:
try:
signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
except ValueError: # ValueError: signal only works in main thread
pass
else:
Pdb._previous_sigint_handler = None
if self.setup(frame, traceback):
# no interaction desired at this time (happens if .pdbrc contains
# a command like "continue")
self.forget()
return
self.print_stack_entry(self.stack[self.curindex])
self._cmdloop()
self.forget()
def displayhook(self, obj):
"""Custom displayhook for the exec in default(), which prevents
assignment of the _ variable in the builtins.
"""
# reproduce the behavior of the standard displayhook, not printing None
if obj is not None:
self.message(repr(obj))
def default(self, line):
if line[:1] == '!': line = line[1:]
locals = self.curframe_locals
globals = self.curframe.f_globals
try:
code = compile(line + '\n', '<stdin>', 'single')
save_stdout = sys.stdout
save_stdin = sys.stdin
save_displayhook = sys.displayhook
try:
sys.stdin = self.stdin
sys.stdout = self.stdout
sys.displayhook = self.displayhook
exec(code, globals, locals)
finally:
sys.stdout = save_stdout
sys.stdin = save_stdin
sys.displayhook = save_displayhook
except:
self._error_exc()
def precmd(self, line):
"""Handle alias expansion and ';;' separator."""
if not line.strip():
return line
args = line.split()
while args[0] in self.aliases:
line = self.aliases[args[0]]
ii = 1
for tmpArg in args[1:]:
line = line.replace("%" + str(ii),
tmpArg)
ii += 1
line = line.replace("%*", ' '.join(args[1:]))
args = line.split()
# split into ';;' separated commands
# unless it's an alias command
if args[0] != 'alias':
marker = line.find(';;')
if marker >= 0:
# queue up everything after marker
next = line[marker+2:].lstrip()
self.cmdqueue.append(next)
line = line[:marker].rstrip()
return line
def onecmd(self, line):
"""Interpret the argument as though it had been typed in response
to the prompt.
Checks whether this line is typed at the normal prompt or in
a breakpoint command list definition.
"""
if not self.commands_defining:
return cmd.Cmd.onecmd(self, line)
else:
return self.handle_command_def(line)
def handle_command_def(self, line):
"""Handles one command line during command list definition."""
cmd, arg, line = self.parseline(line)
if not cmd:
return
if cmd == 'silent':
self.commands_silent[self.commands_bnum] = True
return # continue to handle other cmd def in the cmd list
elif cmd == 'end':
self.cmdqueue = []
return 1 # end of cmd list
cmdlist = self.commands[self.commands_bnum]
if arg:
cmdlist.append(cmd+' '+arg)
else:
cmdlist.append(cmd)
# Determine if we must stop
try:
func = getattr(self, 'do_' + cmd)
except AttributeError:
func = self.default
# one of the resuming commands
if func.__name__ in self.commands_resuming:
self.commands_doprompt[self.commands_bnum] = False
self.cmdqueue = []
return 1
return
# interface abstraction functions
def message(self, msg):
print(msg, file=self.stdout)
def error(self, msg):
print('***', msg, file=self.stdout)
# Generic completion functions. Individual complete_foo methods can be
# assigned below to one of these functions.
def _complete_location(self, text, line, begidx, endidx):
# Complete a file/module/function location for break/tbreak/clear.
if line.strip().endswith((':', ',')):
# Here comes a line number or a condition which we can't complete.
return []
# First, try to find matching functions (i.e. expressions).
try:
ret = self._complete_expression(text, line, begidx, endidx)
except Exception:
ret = []
# Then, try to complete file names as well.
globs = glob.glob(glob.escape(text) + '*')
for fn in globs:
if os.path.isdir(fn):
ret.append(fn + '/')
elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
ret.append(fn + ':')
return ret
def _complete_bpnumber(self, text, line, begidx, endidx):
# Complete a breakpoint number. (This would be more helpful if we could
# display additional info along with the completions, such as file/line
# of the breakpoint.)
return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
if bp is not None and str(i).startswith(text)]
def _complete_expression(self, text, line, begidx, endidx):
# Complete an arbitrary expression.
if not self.curframe:
return []
# Collect globals and locals. It is usually not really sensible to also
# complete builtins, and they clutter the namespace quite heavily, so we
# leave them out.
ns = {**self.curframe.f_globals, **self.curframe_locals}
if '.' in text:
# Walk an attribute chain up to the last part, similar to what
# rlcompleter does. This will bail if any of the parts are not
# simple attribute access, which is what we want.
dotted = text.split('.')
try:
obj = ns[dotted[0]]
for part in dotted[1:-1]:
obj = getattr(obj, part)
except (KeyError, AttributeError):
return []
prefix = '.'.join(dotted[:-1]) + '.'
return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
else:
# Complete a simple name.
return [n for n in ns.keys() if n.startswith(text)]
# Command definitions, called by cmdloop()
# The argument is the remaining string on the command line
# Return true to exit from the command loop
def do_commands(self, arg):
"""commands [bpnumber]
(com) ...
(com) end
(Pdb)
Specify a list of commands for breakpoint number bpnumber.
The commands themselves are entered on the following lines.
Type a line containing just 'end' to terminate the commands.
The commands are executed when the breakpoint is hit.
To remove all commands from a breakpoint, type commands and
follow it immediately with end; that is, give no commands.
With no bpnumber argument, commands refers to the last
breakpoint set.
You can use breakpoint commands to start your program up
again. Simply use the continue command, or step, or any other
command that resumes execution.
Specifying any command resuming execution (currently continue,
step, next, return, jump, quit and their abbreviations)
terminates the command list (as if that command was
immediately followed by end). This is because any time you
resume execution (even with a simple next or step), you may
encounter another breakpoint -- which could have its own
command list, leading to ambiguities about which list to
execute.
If you use the 'silent' command in the command list, the usual
message about stopping at a breakpoint is not printed. This
may be desirable for breakpoints that are to print a specific
message and then continue. If none of the other commands
print anything, you will see no sign that the breakpoint was
reached.
"""
if not arg:
bnum = len(bdb.Breakpoint.bpbynumber) - 1
else:
try:
bnum = int(arg)
except:
self.error("Usage: commands [bnum]\n ...\n end")
return
self.commands_bnum = bnum
# Save old definitions for the case of a keyboard interrupt.
if bnum in self.commands:
old_command_defs = (self.commands[bnum],
self.commands_doprompt[bnum],
self.commands_silent[bnum])
else:
old_command_defs = None
self.commands[bnum] = []
self.commands_doprompt[bnum] = True
self.commands_silent[bnum] = False
prompt_back = self.prompt
self.prompt = '(com) '
self.commands_defining = True
try:
self.cmdloop()
except KeyboardInterrupt:
# Restore old definitions.
if old_command_defs:
self.commands[bnum] = old_command_defs[0]
self.commands_doprompt[bnum] = old_command_defs[1]
self.commands_silent[bnum] = old_command_defs[2]
else:
del self.commands[bnum]
del self.commands_doprompt[bnum]
del self.commands_silent[bnum]
self.error('command definition aborted, old commands restored')
finally:
self.commands_defining = False
self.prompt = prompt_back
complete_commands = _complete_bpnumber
def do_break(self, arg, temporary = 0):
"""b(reak) [ ([filename:]lineno | function) [, condition] ]
Without argument, list all breaks.
With a line number argument, set a break at this line in the
current file. With a function name, set a break at the first
executable line of that function. If a second argument is
present, it is a string specifying an expression which must
evaluate to true before the breakpoint is honored.
The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet). The file is searched for on
sys.path; the .py suffix may be omitted.
"""
if not arg:
if self.breaks: # There's at least one
self.message("Num Type Disp Enb Where")
for bp in bdb.Breakpoint.bpbynumber:
if bp:
self.message(bp.bpformat())
return
# parse arguments; comma has lowest precedence
# and cannot occur in filename
filename = None
lineno = None
cond = None
comma = arg.find(',')
if comma > 0:
# parse stuff after comma: "condition"
cond = arg[comma+1:].lstrip()
arg = arg[:comma].rstrip()
# parse stuff before comma: [filename:]lineno | function
colon = arg.rfind(':')
funcname = None
if colon >= 0:
filename = arg[:colon].rstrip()
f = self.lookupmodule(filename)
if not f:
self.error('%r not found from sys.path' % filename)
return
else:
filename = f
arg = arg[colon+1:].lstrip()
try:
lineno = int(arg)
except ValueError:
self.error('Bad lineno: %s' % arg)
return
else:
# no colon; can be lineno or function
try:
lineno = int(arg)
except ValueError:
try:
func = eval(arg,
self.curframe.f_globals,
self.curframe_locals)
except:
func = arg
try:
if hasattr(func, '__func__'):
func = func.__func__
code = func.__code__
#use co_name to identify the bkpt (function names
#could be aliased, but co_name is invariant)
funcname = code.co_name
lineno = code.co_firstlineno
filename = code.co_filename
except:
# last thing to try
(ok, filename, ln) = self.lineinfo(arg)
if not ok:
self.error('The specified object %r is not a function '
'or was not found along sys.path.' % arg)
return
funcname = ok # ok contains a function name
lineno = int(ln)
if not filename:
filename = self.defaultFile()
# Check for reasonable breakpoint
line = self.checkline(filename, lineno)
if line:
# now set the break point
err = self.set_break(filename, line, temporary, cond, funcname)
if err:
self.error(err)
else:
bp = self.get_breaks(filename, line)[-1]
self.message("Breakpoint %d at %s:%d" %
(bp.number, bp.file, bp.line))
# To be overridden in derived debuggers
def defaultFile(self):
"""Produce a reasonable default."""
filename = self.curframe.f_code.co_filename
if filename == '<string>' and self.mainpyfile:
filename = self.mainpyfile
return filename
do_b = do_break
complete_break = _complete_location
complete_b = _complete_location
def do_tbreak(self, arg):
"""tbreak [ ([filename:]lineno | function) [, condition] ]
Same arguments as break, but sets a temporary breakpoint: it
is automatically deleted when first hit.
"""
self.do_break(arg, 1)
complete_tbreak = _complete_location
def lineinfo(self, identifier):
failed = (None, None, None)
# Input is identifier, may be in single quotes
idstring = identifier.split("'")
if len(idstring) == 1:
# not in single quotes
id = idstring[0].strip()
elif len(idstring) == 3:
# quoted
id = idstring[1].strip()
else:
return failed
if id == '': return failed
parts = id.split('.')
# Protection for derived debuggers
if parts[0] == 'self':
del parts[0]
if len(parts) == 0:
return failed
# Best first guess at file to look at
fname = self.defaultFile()
if len(parts) == 1:
item = parts[0]
else:
# More than one part.
# First is module, second is method/class
f = self.lookupmodule(parts[0])
if f:
fname = f
item = parts[1]
answer = find_function(item, fname)
return answer or failed
def checkline(self, filename, lineno):
"""Check whether specified line seems to be executable.
Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
line or EOF). Warning: testing is not comprehensive.
"""
# this method should be callable before starting debugging, so default
# to "no globals" if there is no current frame
frame = getattr(self, 'curframe', None)
globs = frame.f_globals if frame else None
line = linecache.getline(filename, lineno, globs)
if not line:
self.message('End of file')
return 0
line = line.strip()
# Don't allow setting breakpoint at a blank line
if (not line or (line[0] == '#') or
(line[:3] == '"""') or line[:3] == "'''"):
self.error('Blank or comment')
return 0
return lineno
def do_enable(self, arg):
"""enable bpnumber [bpnumber ...]
Enables the breakpoints given as a space separated list of
breakpoint numbers.
"""
args = arg.split()
for i in args:
try:
bp = self.get_bpbynumber(i)
except ValueError as err:
self.error(err)
else:
bp.enable()
self.message('Enabled %s' % bp)
complete_enable = _complete_bpnumber
def do_disable(self, arg):
"""disable bpnumber [bpnumber ...]
Disables the breakpoints given as a space separated list of
breakpoint numbers. Disabling a breakpoint means it cannot
cause the program to stop execution, but unlike clearing a
breakpoint, it remains in the list of breakpoints and can be
(re-)enabled.
"""
args = arg.split()
for i in args:
try:
bp = self.get_bpbynumber(i)
except ValueError as err:
self.error(err)
else:
bp.disable()
self.message('Disabled %s' % bp)
complete_disable = _complete_bpnumber
def do_condition(self, arg):
"""condition bpnumber [condition]
Set a new condition for the breakpoint, an expression which
must evaluate to true before the breakpoint is honored. If
condition is absent, any existing condition is removed; i.e.,
the breakpoint is made unconditional.
"""
args = arg.split(' ', 1)
try:
cond = args[1]
except IndexError:
cond = None
try:
bp = self.get_bpbynumber(args[0].strip())
except IndexError:
self.error('Breakpoint number expected')
except ValueError as err:
self.error(err)
else:
bp.cond = cond
if not cond:
self.message('Breakpoint %d is now unconditional.' % bp.number)
else:
self.message('New condition set for breakpoint %d.' % bp.number)
complete_condition = _complete_bpnumber
def do_ignore(self, arg):
"""ignore bpnumber [count]
Set the ignore count for the given breakpoint number. If
count is omitted, the ignore count is set to 0. A breakpoint
becomes active when the ignore count is zero. When non-zero,
the count is decremented each time the breakpoint is reached
and the breakpoint is not disabled and any associated
condition evaluates to true.
"""
args = arg.split()
try:
count = int(args[1].strip())
except:
count = 0
try:
bp = self.get_bpbynumber(args[0].strip())
except IndexError:
self.error('Breakpoint number expected')
except ValueError as err:
self.error(err)
else:
bp.ignore = count
if count > 0:
if count > 1:
countstr = '%d crossings' % count
else:
countstr = '1 crossing'
self.message('Will ignore next %s of breakpoint %d.' %
(countstr, bp.number))
else:
self.message('Will stop next time breakpoint %d is reached.'
% bp.number)
complete_ignore = _complete_bpnumber
def do_clear(self, arg):
"""cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
With a space separated list of breakpoint numbers, clear
those breakpoints. Without argument, clear all breaks (but
first ask confirmation). With a filename:lineno argument,
clear all breaks at that line in that file.
"""
if not arg:
try:
reply = input('Clear all breaks? ')
except EOFError:
reply = 'no'
reply = reply.strip().lower()
if reply in ('y', 'yes'):
bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
self.clear_all_breaks()
for bp in bplist:
self.message('Deleted %s' % bp)
return
if ':' in arg:
# Make sure it works for "clear C:\foo\bar.py:12"
i = arg.rfind(':')
filename = arg[:i]
arg = arg[i+1:]
try:
lineno = int(arg)
except ValueError:
err = "Invalid line number (%s)" % arg
else:
bplist = self.get_breaks(filename, lineno)[:]
err = self.clear_break(filename, lineno)
if err:
self.error(err)
else:
for bp in bplist:
self.message('Deleted %s' % bp)
return
numberlist = arg.split()
for i in numberlist:
try:
bp = self.get_bpbynumber(i)
except ValueError as err:
self.error(err)
else:
self.clear_bpbynumber(i)
self.message('Deleted %s' % bp)
do_cl = do_clear # 'c' is already an abbreviation for 'continue'
complete_clear = _complete_location
complete_cl = _complete_location
def do_where(self, arg):
"""w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
context of most commands. 'bt' is an alias for this command.
"""
self.print_stack_trace()
do_w = do_where
do_bt = do_where
def _select_frame(self, number):
assert 0 <= number < len(self.stack)
self.curindex = number
self.curframe = self.stack[self.curindex][0]
self.curframe_locals = self.curframe.f_locals
self.print_stack_entry(self.stack[self.curindex])
self.lineno = None
def do_up(self, arg):
"""u(p) [count]
Move the current frame count (default one) levels up in the
stack trace (to an older frame).
"""
if self.curindex == 0:
self.error('Oldest frame')
return
try:
count = int(arg or 1)
except ValueError:
self.error('Invalid frame count (%s)' % arg)
return
if count < 0:
newframe = 0
else:
newframe = max(0, self.curindex - count)
self._select_frame(newframe)
do_u = do_up
def do_down(self, arg):
"""d(own) [count]
Move the current frame count (default one) levels down in the
stack trace (to a newer frame).
"""
if self.curindex + 1 == len(self.stack):
self.error('Newest frame')
return
try:
count = int(arg or 1)
except ValueError:
self.error('Invalid frame count (%s)' % arg)
return
if count < 0:
newframe = len(self.stack) - 1
else:
newframe = min(len(self.stack) - 1, self.curindex + count)
self._select_frame(newframe)
do_d = do_down
def do_until(self, arg):
"""unt(il) [lineno]
Without argument, continue execution until the line with a
number greater than the current one is reached. With a line
number, continue execution until a line with a number greater
or equal to that is reached. In both cases, also stop when
the current frame returns.
"""
if arg:
try:
lineno = int(arg)
except ValueError:
self.error('Error in argument: %r' % arg)
return
if lineno <= self.curframe.f_lineno:
self.error('"until" line number is smaller than current '
'line number')
return
else:
lineno = None
self.set_until(self.curframe, lineno)
return 1
do_unt = do_until
def do_step(self, arg):
"""s(tep)
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current
function).
"""
self.set_step()
return 1
do_s = do_step
def do_next(self, arg):
"""n(ext)
Continue execution until the next line in the current function
is reached or it returns.
"""
self.set_next(self.curframe)
return 1
do_n = do_next
def do_run(self, arg):
"""run [args...]
Restart the debugged python program. If a string is supplied
it is split with "shlex", and the result is used as the new
sys.argv. History, breakpoints, actions and debugger options
are preserved. "restart" is an alias for "run".
"""
if arg:
import shlex
argv0 = sys.argv[0:1]
try:
sys.argv = shlex.split(arg)
except ValueError as e:
self.error('Cannot run %s: %s' % (arg, e))
return
sys.argv[:0] = argv0
# this is caught in the main debugger loop
raise Restart
do_restart = do_run
def do_return(self, arg):
"""r(eturn)
Continue execution until the current function returns.
"""
self.set_return(self.curframe)
return 1
do_r = do_return
def do_continue(self, arg):
"""c(ont(inue))
Continue execution, only stop when a breakpoint is encountered.
"""
if not self.nosigint:
try:
Pdb._previous_sigint_handler = \
signal.signal(signal.SIGINT, self.sigint_handler)
except ValueError:
# ValueError happens when do_continue() is invoked from
# a non-main thread in which case we just continue without
# SIGINT set. Would printing a message here (once) make
# sense?
pass
self.set_continue()
return 1
do_c = do_cont = do_continue
def do_jump(self, arg):
"""j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are allowed -- for
instance it is not possible to jump into the middle of a
for loop or out of a finally clause.
"""
if self.curindex + 1 != len(self.stack):
self.error('You can only jump within the bottom frame')
return
try:
arg = int(arg)
except ValueError:
self.error("The 'jump' command requires a line number")
else:
try:
# Do the jump, fix up our copy of the stack, and display the
# new position
self.curframe.f_lineno = arg
self.stack[self.curindex] = self.stack[self.curindex][0], arg
self.print_stack_entry(self.stack[self.curindex])
except ValueError as e:
self.error('Jump failed: %s' % e)
do_j = do_jump
def do_debug(self, arg):
"""debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment).
"""
sys.settrace(None)
globals = self.curframe.f_globals
locals = self.curframe_locals
p = Pdb(self.completekey, self.stdin, self.stdout)
p.prompt = "(%s) " % self.prompt.strip()
self.message("ENTERING RECURSIVE DEBUGGER")
try:
sys.call_tracing(p.run, (arg, globals, locals))
except Exception:
self._error_exc()
self.message("LEAVING RECURSIVE DEBUGGER")
sys.settrace(self.trace_dispatch)
self.lastcmd = p.lastcmd
complete_debug = _complete_expression
def do_quit(self, arg):
"""q(uit)\nexit
Quit from the debugger. The program being executed is aborted.
"""
self._user_requested_quit = True
self.set_quit()
return 1
do_q = do_quit
do_exit = do_quit
def do_EOF(self, arg):
"""EOF
Handles the receipt of EOF as a command.
"""
self.message('')
self._user_requested_quit = True
self.set_quit()
return 1
def do_args(self, arg):
"""a(rgs)
Print the argument list of the current function.
"""
co = self.curframe.f_code
dict = self.curframe_locals
n = co.co_argcount + co.co_kwonlyargcount
if co.co_flags & inspect.CO_VARARGS: n = n+1
if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1
for i in range(n):
name = co.co_varnames[i]
if name in dict:
self.message('%s = %r' % (name, dict[name]))
else:
self.message('%s = *** undefined ***' % (name,))
do_a = do_args
def do_retval(self, arg):
"""retval
Print the return value for the last return of a function.
"""
if '__return__' in self.curframe_locals:
self.message(repr(self.curframe_locals['__return__']))
else:
self.error('Not yet returned!')
do_rv = do_retval
def _getval(self, arg):
try:
return eval(arg, self.curframe.f_globals, self.curframe_locals)
except:
self._error_exc()
raise
def _getval_except(self, arg, frame=None):
try:
if frame is None:
return eval(arg, self.curframe.f_globals, self.curframe_locals)
else:
return eval(arg, frame.f_globals, frame.f_locals)
except:
exc_info = sys.exc_info()[:2]
err = traceback.format_exception_only(*exc_info)[-1].strip()
return _rstr('** raised %s **' % err)
def _error_exc(self):
exc_info = sys.exc_info()[:2]
self.error(traceback.format_exception_only(*exc_info)[-1].strip())
def _msg_val_func(self, arg, func):
try:
val = self._getval(arg)
except:
return # _getval() has displayed the error
try:
self.message(func(val))
except:
self._error_exc()
def do_p(self, arg):
"""p expression
Print the value of the expression.
"""
self._msg_val_func(arg, repr)
def do_pp(self, arg):
"""pp expression
Pretty-print the value of the expression.
"""
self._msg_val_func(arg, pprint.pformat)
complete_print = _complete_expression
complete_p = _complete_expression
complete_pp = _complete_expression
def do_list(self, arg):
"""l(ist) [first [,last] | .]
List source code for the current file. Without arguments,
list 11 lines around the current line or continue the previous
listing. With . as argument, list 11 lines around the current
line. With one argument, list 11 lines starting at that line.
With two arguments, list the given range; if the second
argument is less than the first, it is a count.
The current line in the current frame is indicated by "->".
If an exception is being debugged, the line where the
exception was originally raised or propagated is indicated by
">>", if it differs from the current line.
"""
self.lastcmd = 'list'
last = None
if arg and arg != '.':
try:
if ',' in arg:
first, last = arg.split(',')
first = int(first.strip())
last = int(last.strip())
if last < first:
# assume it's a count
last = first + last
else:
first = int(arg.strip())
first = max(1, first - 5)
except ValueError:
self.error('Error in argument: %r' % arg)
return
elif self.lineno is None or arg == '.':
first = max(1, self.curframe.f_lineno - 5)
else:
first = self.lineno + 1
if last is None:
last = first + 10
filename = self.curframe.f_code.co_filename
# gh-93696: stdlib frozen modules provide a useful __file__
# this workaround can be removed with the closure of gh-89815
if filename.startswith("<frozen"):
tmp = self.curframe.f_globals.get("__file__")
if isinstance(tmp, str):
filename = tmp
breaklist = self.get_file_breaks(filename)
try:
lines = linecache.getlines(filename, self.curframe.f_globals)
self._print_lines(lines[first-1:last], first, breaklist,
self.curframe)
self.lineno = min(last, len(lines))
if len(lines) < last:
self.message('[EOF]')
except KeyboardInterrupt:
pass
do_l = do_list
def do_longlist(self, arg):
"""longlist | ll
List the whole source code for the current function or frame.
"""
filename = self.curframe.f_code.co_filename
breaklist = self.get_file_breaks(filename)
try:
lines, lineno = inspect.getsourcelines(self.curframe)
except OSError as err:
self.error(err)
return
self._print_lines(lines, lineno, breaklist, self.curframe)
do_ll = do_longlist
def do_source(self, arg):
"""source expression
Try to get source code for the given object and display it.
"""
try:
obj = self._getval(arg)
except:
return
try:
lines, lineno = inspect.getsourcelines(obj)
except (OSError, TypeError) as err:
self.error(err)
return
self._print_lines(lines, lineno)
complete_source = _complete_expression
def _print_lines(self, lines, start, breaks=(), frame=None):
"""Print a range of lines."""
if frame:
current_lineno = frame.f_lineno
exc_lineno = self.tb_lineno.get(frame, -1)
else:
current_lineno = exc_lineno = -1
for lineno, line in enumerate(lines, start):
s = str(lineno).rjust(3)
if len(s) < 4:
s += ' '
if lineno in breaks:
s += 'B'
else:
s += ' '
if lineno == current_lineno:
s += '->'
elif lineno == exc_lineno:
s += '>>'
self.message(s + '\t' + line.rstrip())
def do_whatis(self, arg):
"""whatis arg
Print the type of the argument.
"""
try:
value = self._getval(arg)
except:
# _getval() already printed the error
return
code = None
# Is it an instance method?
try:
code = value.__func__.__code__
except Exception:
pass
if code:
self.message('Method %s' % code.co_name)
return
# Is it a function?
try:
code = value.__code__
except Exception:
pass
if code:
self.message('Function %s' % code.co_name)
return
# Is it a class?
if value.__class__ is type:
self.message('Class %s.%s' % (value.__module__, value.__qualname__))
return
# None of the above...
self.message(type(value))
complete_whatis = _complete_expression
def do_display(self, arg):
"""display [expression]
Display the value of the expression if it changed, each time execution
stops in the current frame.
Without expression, list all display expressions for the current frame.
"""
if not arg:
self.message('Currently displaying:')
for item in self.displaying.get(self.curframe, {}).items():
self.message('%s: %r' % item)
else:
val = self._getval_except(arg)
self.displaying.setdefault(self.curframe, {})[arg] = val
self.message('display %s: %r' % (arg, val))
complete_display = _complete_expression
def do_undisplay(self, arg):
"""undisplay [expression]
Do not display the expression any more in the current frame.
Without expression, clear all display expressions for the current frame.
"""
if arg:
try:
del self.displaying.get(self.curframe, {})[arg]
except KeyError:
self.error('not displaying %s' % arg)
else:
self.displaying.pop(self.curframe, None)
def complete_undisplay(self, text, line, begidx, endidx):
return [e for e in self.displaying.get(self.curframe, {})
if e.startswith(text)]
def do_interact(self, arg):
"""interact
Start an interactive interpreter whose global namespace
contains all the (global and local) names found in the current scope.
"""
ns = {**self.curframe.f_globals, **self.curframe_locals}
code.interact("*interactive*", local=ns)
def do_alias(self, arg):
"""alias [name [command [parameter parameter ...] ]]
Create an alias called 'name' that executes 'command'. The
command must *not* be enclosed in quotes. Replaceable
parameters can be indicated by %1, %2, and so on, while %* is
replaced by all the parameters. If no command is given, the
current alias for name is shown. If no name is given, all
aliases are listed.
Aliases may be nested and can contain anything that can be
legally typed at the pdb prompt. Note! You *can* override
internal pdb commands with aliases! Those internal commands
are then hidden until the alias is removed. Aliasing is
recursively applied to the first word of the command line; all
other words in the line are left alone.
As an example, here are two useful aliases (especially when
placed in the .pdbrc file):
# Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
# Print instance variables in self
alias ps pi self
"""
args = arg.split()
if len(args) == 0:
keys = sorted(self.aliases.keys())
for alias in keys:
self.message("%s = %s" % (alias, self.aliases[alias]))
return
if args[0] in self.aliases and len(args) == 1:
self.message("%s = %s" % (args[0], self.aliases[args[0]]))
else:
self.aliases[args[0]] = ' '.join(args[1:])
def do_unalias(self, arg):
"""unalias name
Delete the specified alias.
"""
args = arg.split()
if len(args) == 0: return
if args[0] in self.aliases:
del self.aliases[args[0]]
def complete_unalias(self, text, line, begidx, endidx):
return [a for a in self.aliases if a.startswith(text)]
# List of all the commands making the program resume execution.
commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
'do_quit', 'do_jump']
# Print a traceback starting at the top stack frame.
# The most recently entered frame is printed last;
# this is different from dbx and gdb, but consistent with
# the Python interpreter's stack trace.
# It is also consistent with the up/down commands (which are
# compatible with dbx and gdb: up moves towards 'main()'
# and down moves towards the most recent stack frame).
def print_stack_trace(self):
try:
for frame_lineno in self.stack:
self.print_stack_entry(frame_lineno)
except KeyboardInterrupt:
pass
def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
frame, lineno = frame_lineno
if frame is self.curframe:
prefix = '> '
else:
prefix = ' '
self.message(prefix +
self.format_stack_entry(frame_lineno, prompt_prefix))
# Provide help
def do_help(self, arg):
"""h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command.
"help pdb" shows the full pdb documentation.
"help exec" gives help on the ! command.
"""
if not arg:
return cmd.Cmd.do_help(self, arg)
try:
try:
topic = getattr(self, 'help_' + arg)
return topic()
except AttributeError:
command = getattr(self, 'do_' + arg)
except AttributeError:
self.error('No help for %r' % arg)
else:
if sys.flags.optimize >= 2:
self.error('No help for %r; please do not run Python with -OO '
'if you need command help' % arg)
return
if command.__doc__ is None:
self.error('No help for %r; __doc__ string missing' % arg)
return
self.message(command.__doc__.rstrip())
do_h = do_help
def help_exec(self):
"""(!) statement
Execute the (one-line) statement in the context of the current
stack frame. The exclamation point can be omitted unless the
first word of the statement resembles a debugger command. To
assign to a global variable you must always prefix the command
with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
(Pdb)
"""
self.message((self.help_exec.__doc__ or '').strip())
def help_pdb(self):
help()
# other helper functions
def lookupmodule(self, filename):
"""Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (possibly incomplete) file or module name
into an absolute file name.
"""
if os.path.isabs(filename) and os.path.exists(filename):
return filename
f = os.path.join(sys.path[0], filename)
if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
return f
root, ext = os.path.splitext(filename)
if ext == '':
filename = filename + '.py'
if os.path.isabs(filename):
return filename
for dirname in sys.path:
while os.path.islink(dirname):
dirname = os.readlink(dirname)
fullname = os.path.join(dirname, filename)
if os.path.exists(fullname):
return fullname
return None
def _runmodule(self, module_name):
self._wait_for_mainpyfile = True
self._user_requested_quit = False
import runpy
mod_name, mod_spec, code = runpy._get_module_details(module_name)
self.mainpyfile = self.canonic(code.co_filename)
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": self.mainpyfile,
"__package__": mod_spec.parent,
"__loader__": mod_spec.loader,
"__spec__": mod_spec,
"__builtins__": __builtins__,
})
self.run(code)
def _runscript(self, filename):
# The script has to run in __main__ namespace (or imports from
# __main__ will break).
#
# So we clear up the __main__ and set several special variables
# (this gets rid of pdb's globals and cleans old variables on restarts).
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({"__name__" : "__main__",
"__file__" : filename,
"__builtins__": __builtins__,
})
# When bdb sets tracing, a number of call and line events happens
# BEFORE debugger even reaches user's code (and the exact sequence of
# events depends on python version). So we take special measures to
# avoid stopping before we reach the main script (see user_line and
# user_call for details).
self._wait_for_mainpyfile = True
self.mainpyfile = self.canonic(filename)
self._user_requested_quit = False
with io.open_code(filename) as fp:
statement = "exec(compile(%r, %r, 'exec'))" % \
(fp.read(), self.mainpyfile)
self.run(statement)
|
(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True)
|
706,604
|
pdb
|
__init__
| null |
def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
nosigint=False, readrc=True):
bdb.Bdb.__init__(self, skip=skip)
cmd.Cmd.__init__(self, completekey, stdin, stdout)
sys.audit("pdb.Pdb")
if stdout:
self.use_rawinput = 0
self.prompt = '(Pdb) '
self.aliases = {}
self.displaying = {}
self.mainpyfile = ''
self._wait_for_mainpyfile = False
self.tb_lineno = {}
# Try to load readline if it exists
try:
import readline
# remove some common file name delimiters
readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
except ImportError:
pass
self.allow_kbdint = False
self.nosigint = nosigint
# Read ~/.pdbrc and ./.pdbrc
self.rcLines = []
if readrc:
try:
with open(os.path.expanduser('~/.pdbrc')) as rcFile:
self.rcLines.extend(rcFile)
except OSError:
pass
try:
with open(".pdbrc") as rcFile:
self.rcLines.extend(rcFile)
except OSError:
pass
self.commands = {} # associates a command list to breakpoint numbers
self.commands_doprompt = {} # for each bp num, tells if the prompt
# must be disp. after execing the cmd list
self.commands_silent = {} # for each bp num, tells if the stack trace
# must be disp. after execing the cmd list
self.commands_defining = False # True while in the process of defining
# a command list
self.commands_bnum = None # The breakpoint number for which we are
# defining a list
|
(self, completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True)
|
706,617
|
pdb
|
_runmodule
| null |
def _runmodule(self, module_name):
self._wait_for_mainpyfile = True
self._user_requested_quit = False
import runpy
mod_name, mod_spec, code = runpy._get_module_details(module_name)
self.mainpyfile = self.canonic(code.co_filename)
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": self.mainpyfile,
"__package__": mod_spec.parent,
"__loader__": mod_spec.loader,
"__spec__": mod_spec,
"__builtins__": __builtins__,
})
self.run(code)
|
(self, module_name)
|
706,618
|
pdb
|
_runscript
| null |
def _runscript(self, filename):
# The script has to run in __main__ namespace (or imports from
# __main__ will break).
#
# So we clear up the __main__ and set several special variables
# (this gets rid of pdb's globals and cleans old variables on restarts).
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({"__name__" : "__main__",
"__file__" : filename,
"__builtins__": __builtins__,
})
# When bdb sets tracing, a number of call and line events happens
# BEFORE debugger even reaches user's code (and the exact sequence of
# events depends on python version). So we take special measures to
# avoid stopping before we reach the main script (see user_line and
# user_call for details).
self._wait_for_mainpyfile = True
self.mainpyfile = self.canonic(filename)
self._user_requested_quit = False
with io.open_code(filename) as fp:
statement = "exec(compile(%r, %r, 'exec'))" % \
(fp.read(), self.mainpyfile)
self.run(statement)
|
(self, filename)
|
706,632
|
cmd
|
complete
|
Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.
|
def complete(self, text, state):
"""Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.
"""
if state == 0:
import readline
origline = readline.get_line_buffer()
line = origline.lstrip()
stripped = len(origline) - len(line)
begidx = readline.get_begidx() - stripped
endidx = readline.get_endidx() - stripped
if begidx>0:
cmd, args, foo = self.parseline(line)
if cmd == '':
compfunc = self.completedefault
else:
try:
compfunc = getattr(self, 'complete_' + cmd)
except AttributeError:
compfunc = self.completedefault
else:
compfunc = self.completenames
self.completion_matches = compfunc(text, line, begidx, endidx)
try:
return self.completion_matches[state]
except IndexError:
return None
|
(self, text, state)
|
706,655
|
pdb
|
default
| null |
def default(self, line):
if line[:1] == '!': line = line[1:]
locals = self.curframe_locals
globals = self.curframe.f_globals
try:
code = compile(line + '\n', '<stdin>', 'single')
save_stdout = sys.stdout
save_stdin = sys.stdin
save_displayhook = sys.displayhook
try:
sys.stdin = self.stdin
sys.stdout = self.stdout
sys.displayhook = self.displayhook
exec(code, globals, locals)
finally:
sys.stdout = save_stdout
sys.stdin = save_stdin
sys.displayhook = save_displayhook
except:
self._error_exc()
|
(self, line)
|
706,668
|
pdb
|
do_where
|
w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
context of most commands. 'bt' is an alias for this command.
|
def do_where(self, arg):
"""w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
context of most commands. 'bt' is an alias for this command.
"""
self.print_stack_trace()
|
(self, arg)
|
706,669
|
pdb
|
do_continue
|
c(ont(inue))
Continue execution, only stop when a breakpoint is encountered.
|
def do_continue(self, arg):
"""c(ont(inue))
Continue execution, only stop when a breakpoint is encountered.
"""
if not self.nosigint:
try:
Pdb._previous_sigint_handler = \
signal.signal(signal.SIGINT, self.sigint_handler)
except ValueError:
# ValueError happens when do_continue() is invoked from
# a non-main thread in which case we just continue without
# SIGINT set. Would printing a message here (once) make
# sense?
pass
self.set_continue()
return 1
|
(self, arg)
|
706,676
|
pdb
|
do_down
|
d(own) [count]
Move the current frame count (default one) levels down in the
stack trace (to a newer frame).
|
def do_down(self, arg):
"""d(own) [count]
Move the current frame count (default one) levels down in the
stack trace (to a newer frame).
"""
if self.curindex + 1 == len(self.stack):
self.error('Newest frame')
return
try:
count = int(arg or 1)
except ValueError:
self.error('Invalid frame count (%s)' % arg)
return
if count < 0:
newframe = len(self.stack) - 1
else:
newframe = min(len(self.stack) - 1, self.curindex + count)
self._select_frame(newframe)
|
(self, arg)
|
706,677
|
pdb
|
do_debug
|
debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment).
|
def do_debug(self, arg):
"""debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment).
"""
sys.settrace(None)
globals = self.curframe.f_globals
locals = self.curframe_locals
p = Pdb(self.completekey, self.stdin, self.stdout)
p.prompt = "(%s) " % self.prompt.strip()
self.message("ENTERING RECURSIVE DEBUGGER")
try:
sys.call_tracing(p.run, (arg, globals, locals))
except Exception:
self._error_exc()
self.message("LEAVING RECURSIVE DEBUGGER")
sys.settrace(self.trace_dispatch)
self.lastcmd = p.lastcmd
|
(self, arg)
|
706,679
|
pdb
|
do_display
|
display [expression]
Display the value of the expression if it changed, each time execution
stops in the current frame.
Without expression, list all display expressions for the current frame.
|
def do_display(self, arg):
"""display [expression]
Display the value of the expression if it changed, each time execution
stops in the current frame.
Without expression, list all display expressions for the current frame.
"""
if not arg:
self.message('Currently displaying:')
for item in self.displaying.get(self.curframe, {}).items():
self.message('%s: %r' % item)
else:
val = self._getval_except(arg)
self.displaying.setdefault(self.curframe, {})[arg] = val
self.message('display %s: %r' % (arg, val))
|
(self, arg)
|
706,686
|
pdb
|
do_interact
|
interact
Start an interactive interpreter whose global namespace
contains all the (global and local) names found in the current scope.
|
def do_interact(self, arg):
"""interact
Start an interactive interpreter whose global namespace
contains all the (global and local) names found in the current scope.
"""
ns = {**self.curframe.f_globals, **self.curframe_locals}
code.interact("*interactive*", local=ns)
|
(self, arg)
|
706,687
|
pdb
|
do_jump
|
j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are allowed -- for
instance it is not possible to jump into the middle of a
for loop or out of a finally clause.
|
def do_jump(self, arg):
"""j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are allowed -- for
instance it is not possible to jump into the middle of a
for loop or out of a finally clause.
"""
if self.curindex + 1 != len(self.stack):
self.error('You can only jump within the bottom frame')
return
try:
arg = int(arg)
except ValueError:
self.error("The 'jump' command requires a line number")
else:
try:
# Do the jump, fix up our copy of the stack, and display the
# new position
self.curframe.f_lineno = arg
self.stack[self.curindex] = self.stack[self.curindex][0], arg
self.print_stack_entry(self.stack[self.curindex])
except ValueError as e:
self.error('Jump failed: %s' % e)
|
(self, arg)
|
706,689
|
pdb
|
do_list
|
l(ist) [first [,last] | .]
List source code for the current file. Without arguments,
list 11 lines around the current line or continue the previous
listing. With . as argument, list 11 lines around the current
line. With one argument, list 11 lines starting at that line.
With two arguments, list the given range; if the second
argument is less than the first, it is a count.
The current line in the current frame is indicated by "->".
If an exception is being debugged, the line where the
exception was originally raised or propagated is indicated by
">>", if it differs from the current line.
|
def do_list(self, arg):
"""l(ist) [first [,last] | .]
List source code for the current file. Without arguments,
list 11 lines around the current line or continue the previous
listing. With . as argument, list 11 lines around the current
line. With one argument, list 11 lines starting at that line.
With two arguments, list the given range; if the second
argument is less than the first, it is a count.
The current line in the current frame is indicated by "->".
If an exception is being debugged, the line where the
exception was originally raised or propagated is indicated by
">>", if it differs from the current line.
"""
self.lastcmd = 'list'
last = None
if arg and arg != '.':
try:
if ',' in arg:
first, last = arg.split(',')
first = int(first.strip())
last = int(last.strip())
if last < first:
# assume it's a count
last = first + last
else:
first = int(arg.strip())
first = max(1, first - 5)
except ValueError:
self.error('Error in argument: %r' % arg)
return
elif self.lineno is None or arg == '.':
first = max(1, self.curframe.f_lineno - 5)
else:
first = self.lineno + 1
if last is None:
last = first + 10
filename = self.curframe.f_code.co_filename
# gh-93696: stdlib frozen modules provide a useful __file__
# this workaround can be removed with the closure of gh-89815
if filename.startswith("<frozen"):
tmp = self.curframe.f_globals.get("__file__")
if isinstance(tmp, str):
filename = tmp
breaklist = self.get_file_breaks(filename)
try:
lines = linecache.getlines(filename, self.curframe.f_globals)
self._print_lines(lines[first-1:last], first, breaklist,
self.curframe)
self.lineno = min(last, len(lines))
if len(lines) < last:
self.message('[EOF]')
except KeyboardInterrupt:
pass
|
(self, arg)
|
706,691
|
pdb
|
do_longlist
|
longlist | ll
List the whole source code for the current function or frame.
|
def do_longlist(self, arg):
"""longlist | ll
List the whole source code for the current function or frame.
"""
filename = self.curframe.f_code.co_filename
breaklist = self.get_file_breaks(filename)
try:
lines, lineno = inspect.getsourcelines(self.curframe)
except OSError as err:
self.error(err)
return
self._print_lines(lines, lineno, breaklist, self.curframe)
|
(self, arg)
|
706,693
|
pdb
|
do_next
|
n(ext)
Continue execution until the next line in the current function
is reached or it returns.
|
def do_next(self, arg):
"""n(ext)
Continue execution until the next line in the current function
is reached or it returns.
"""
self.set_next(self.curframe)
return 1
|
(self, arg)
|
706,695
|
pdb
|
do_p
|
p expression
Print the value of the expression.
|
def do_p(self, arg):
"""p expression
Print the value of the expression.
"""
self._msg_val_func(arg, repr)
|
(self, arg)
|
706,696
|
pdb
|
do_pp
|
pp expression
Pretty-print the value of the expression.
|
def do_pp(self, arg):
"""pp expression
Pretty-print the value of the expression.
"""
self._msg_val_func(arg, pprint.pformat)
|
(self, arg)
|
706,700
|
pdb
|
do_run
|
run [args...]
Restart the debugged python program. If a string is supplied
it is split with "shlex", and the result is used as the new
sys.argv. History, breakpoints, actions and debugger options
are preserved. "restart" is an alias for "run".
|
def do_run(self, arg):
"""run [args...]
Restart the debugged python program. If a string is supplied
it is split with "shlex", and the result is used as the new
sys.argv. History, breakpoints, actions and debugger options
are preserved. "restart" is an alias for "run".
"""
if arg:
import shlex
argv0 = sys.argv[0:1]
try:
sys.argv = shlex.split(arg)
except ValueError as e:
self.error('Cannot run %s: %s' % (arg, e))
return
sys.argv[:0] = argv0
# this is caught in the main debugger loop
raise Restart
|
(self, arg)
|
706,705
|
pdb
|
do_step
|
s(tep)
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current
function).
|
def do_step(self, arg):
"""s(tep)
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current
function).
"""
self.set_step()
return 1
|
(self, arg)
|
706,706
|
pdb
|
do_source
|
source expression
Try to get source code for the given object and display it.
|
def do_source(self, arg):
"""source expression
Try to get source code for the given object and display it.
"""
try:
obj = self._getval(arg)
except:
return
try:
lines, lineno = inspect.getsourcelines(obj)
except (OSError, TypeError) as err:
self.error(err)
return
self._print_lines(lines, lineno)
|
(self, arg)
|
706,709
|
pdb
|
do_up
|
u(p) [count]
Move the current frame count (default one) levels up in the
stack trace (to an older frame).
|
def do_up(self, arg):
"""u(p) [count]
Move the current frame count (default one) levels up in the
stack trace (to an older frame).
"""
if self.curindex == 0:
self.error('Oldest frame')
return
try:
count = int(arg or 1)
except ValueError:
self.error('Invalid frame count (%s)' % arg)
return
if count < 0:
newframe = 0
else:
newframe = max(0, self.curindex - count)
self._select_frame(newframe)
|
(self, arg)
|
706,711
|
pdb
|
do_undisplay
|
undisplay [expression]
Do not display the expression any more in the current frame.
Without expression, clear all display expressions for the current frame.
|
def do_undisplay(self, arg):
"""undisplay [expression]
Do not display the expression any more in the current frame.
Without expression, clear all display expressions for the current frame.
"""
if arg:
try:
del self.displaying.get(self.curframe, {})[arg]
except KeyError:
self.error('not displaying %s' % arg)
else:
self.displaying.pop(self.curframe, None)
|
(self, arg)
|
706,712
|
pdb
|
do_until
|
unt(il) [lineno]
Without argument, continue execution until the line with a
number greater than the current one is reached. With a line
number, continue execution until a line with a number greater
or equal to that is reached. In both cases, also stop when
the current frame returns.
|
def do_until(self, arg):
"""unt(il) [lineno]
Without argument, continue execution until the line with a
number greater than the current one is reached. With a line
number, continue execution until a line with a number greater
or equal to that is reached. In both cases, also stop when
the current frame returns.
"""
if arg:
try:
lineno = int(arg)
except ValueError:
self.error('Error in argument: %r' % arg)
return
if lineno <= self.curframe.f_lineno:
self.error('"until" line number is smaller than current '
'line number')
return
else:
lineno = None
self.set_until(self.curframe, lineno)
return 1
|
(self, arg)
|
706,719
|
pdb
|
error
| null |
def error(self, msg):
print('***', msg, file=self.stdout)
|
(self, msg)
|
706,721
|
pdb
|
forget
| null |
def forget(self):
self.lineno = None
self.stack = []
self.curindex = 0
self.curframe = None
self.tb_lineno.clear()
|
(self)
|
706,722
|
bdb
|
format_stack_entry
|
Return a string with information about a stack entry.
The stack entry frame_lineno is a (frame, lineno) tuple. The
return string contains the canonical filename, the function name
or '<lambda>', the input arguments, the return value, and the
line of code (if it exists).
|
def format_stack_entry(self, frame_lineno, lprefix=': '):
"""Return a string with information about a stack entry.
The stack entry frame_lineno is a (frame, lineno) tuple. The
return string contains the canonical filename, the function name
or '<lambda>', the input arguments, the return value, and the
line of code (if it exists).
"""
import linecache, reprlib
frame, lineno = frame_lineno
filename = self.canonic(frame.f_code.co_filename)
s = '%s(%r)' % (filename, lineno)
if frame.f_code.co_name:
s += frame.f_code.co_name
else:
s += "<lambda>"
s += '()'
if '__return__' in frame.f_locals:
rv = frame.f_locals['__return__']
s += '->'
s += reprlib.repr(rv)
if lineno is not None:
line = linecache.getline(filename, lineno, frame.f_globals)
if line:
s += lprefix + line.strip()
return s
|
(self, frame_lineno, lprefix=': ')
|
706,729
|
bdb
|
get_stack
|
Return a list of (frame, lineno) in a stack trace and a size.
List starts with original calling frame, if there is one.
Size may be number of frames above or below f.
|
def get_stack(self, f, t):
"""Return a list of (frame, lineno) in a stack trace and a size.
List starts with original calling frame, if there is one.
Size may be number of frames above or below f.
"""
stack = []
if t and t.tb_frame is f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
if f is self.botframe:
break
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
while t is not None:
stack.append((t.tb_frame, t.tb_lineno))
t = t.tb_next
if f is None:
i = max(0, len(stack) - 1)
return stack, i
|
(self, f, t)
|
706,733
|
pdb
|
interaction
| null |
def interaction(self, frame, traceback):
# Restore the previous signal handler at the Pdb prompt.
if Pdb._previous_sigint_handler:
try:
signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
except ValueError: # ValueError: signal only works in main thread
pass
else:
Pdb._previous_sigint_handler = None
if self.setup(frame, traceback):
# no interaction desired at this time (happens if .pdbrc contains
# a command like "continue")
self.forget()
return
self.print_stack_entry(self.stack[self.curindex])
self._cmdloop()
self.forget()
|
(self, frame, traceback)
|
706,734
|
bdb
|
is_skipped_module
|
Return True if module_name matches any skip pattern.
|
def is_skipped_module(self, module_name):
"Return True if module_name matches any skip pattern."
if module_name is None: # some modules do not have names
return False
for pattern in self.skip:
if fnmatch.fnmatch(module_name, pattern):
return True
return False
|
(self, module_name)
|
706,739
|
cmd
|
parseline
|
Parse the line into a command name and a string containing
the arguments. Returns a tuple containing (command, args, line).
'command' and 'args' may be None if the line couldn't be parsed.
|
def parseline(self, line):
"""Parse the line into a command name and a string containing
the arguments. Returns a tuple containing (command, args, line).
'command' and 'args' may be None if the line couldn't be parsed.
"""
line = line.strip()
if not line:
return None, None, line
elif line[0] == '?':
line = 'help ' + line[1:]
elif line[0] == '!':
if hasattr(self, 'do_shell'):
line = 'shell ' + line[1:]
else:
return None, None, line
i, n = 0, len(line)
while i < n and line[i] in self.identchars: i = i+1
cmd, arg = line[:i], line[i:].strip()
return cmd, arg, line
|
(self, line)
|
706,743
|
pdb
|
preloop
| null |
def preloop(self):
displaying = self.displaying.get(self.curframe)
if displaying:
for expr, oldvalue in displaying.items():
newvalue = self._getval_except(expr)
# check for identity first; this prevents custom __eq__ to
# be called at every loop, and also prevents instances whose
# fields are changed to be displayed
if newvalue is not oldvalue and newvalue != oldvalue:
displaying[expr] = newvalue
self.message('display %s: %r [old: %r]' %
(expr, newvalue, oldvalue))
|
(self)
|
706,744
|
pdb
|
print_stack_entry
| null |
def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
frame, lineno = frame_lineno
if frame is self.curframe:
prefix = '> '
else:
prefix = ' '
self.message(prefix +
self.format_stack_entry(frame_lineno, prompt_prefix))
|
(self, frame_lineno, prompt_prefix='\n-> ')
|
706,745
|
pdb
|
print_stack_trace
| null |
def print_stack_trace(self):
try:
for frame_lineno in self.stack:
self.print_stack_entry(frame_lineno)
except KeyboardInterrupt:
pass
|
(self)
|
706,758
|
bdb
|
set_trace
|
Start debugging from frame.
If frame is not specified, debugging starts from caller's frame.
|
def set_trace(self, frame=None):
"""Start debugging from frame.
If frame is not specified, debugging starts from caller's frame.
"""
if frame is None:
frame = sys._getframe().f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch)
|
(self, frame=None)
|
706,760
|
pdb
|
setup
| null |
def setup(self, f, tb):
self.forget()
self.stack, self.curindex = self.get_stack(f, tb)
while tb:
# when setting up post-mortem debugging with a traceback, save all
# the original line numbers to be displayed along the current line
# numbers (which can be different, e.g. due to finally clauses)
lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
self.tb_lineno[tb.tb_frame] = lineno
tb = tb.tb_next
self.curframe = self.stack[self.curindex][0]
# The f_locals dictionary is updated from the actual frame
# locals whenever the .f_locals accessor is called, so we
# cache it here to ensure that modifications are not overwritten.
self.curframe_locals = self.curframe.f_locals
return self.execRcLines()
|
(self, f, tb)
|
706,768
|
remote_pdb
|
RemotePdb
|
This will run pdb as a ephemeral telnet service. Once you connect no one
else can connect. On construction this object will block execution till a
client has connected.
Based on https://github.com/tamentis/rpdb I think ...
To use this::
RemotePdb(host='0.0.0.0', port=4444).set_trace()
Then run: telnet 127.0.0.1 4444
|
class RemotePdb(Pdb):
"""
This will run pdb as a ephemeral telnet service. Once you connect no one
else can connect. On construction this object will block execution till a
client has connected.
Based on https://github.com/tamentis/rpdb I think ...
To use this::
RemotePdb(host='0.0.0.0', port=4444).set_trace()
Then run: telnet 127.0.0.1 4444
"""
active_instance = None
def __init__(self, host, port, patch_stdstreams=False, quiet=False):
self._quiet = quiet
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
listen_socket.bind((host, port))
if not self._quiet:
cry("RemotePdb session open at %s:%s, waiting for connection ..." % listen_socket.getsockname())
listen_socket.listen(1)
connection, address = listen_socket.accept()
if not self._quiet:
cry("RemotePdb accepted connection from %s." % repr(address))
self.handle = LF2CRLF_FileWrapper(connection)
Pdb.__init__(self, completekey='tab', stdin=self.handle, stdout=self.handle)
self.backup = []
if patch_stdstreams:
for name in (
'stderr',
'stdout',
'__stderr__',
'__stdout__',
'stdin',
'__stdin__',
):
self.backup.append((name, getattr(sys, name)))
setattr(sys, name, self.handle)
RemotePdb.active_instance = self
def __restore(self):
if self.backup and not self._quiet:
cry('Restoring streams: %s ...' % self.backup)
for name, fh in self.backup:
setattr(sys, name, fh)
self.handle.close()
RemotePdb.active_instance = None
def do_quit(self, arg):
self.__restore()
return Pdb.do_quit(self, arg)
do_q = do_exit = do_quit
def set_trace(self, frame=None):
if frame is None:
frame = sys._getframe().f_back
try:
Pdb.set_trace(self, frame)
except IOError as exc:
if exc.errno != errno.ECONNRESET:
raise
|
(host, port, patch_stdstreams=False, quiet=False)
|
706,769
|
remote_pdb
|
__restore
| null |
def __restore(self):
if self.backup and not self._quiet:
cry('Restoring streams: %s ...' % self.backup)
for name, fh in self.backup:
setattr(sys, name, fh)
self.handle.close()
RemotePdb.active_instance = None
|
(self)
|
706,770
|
remote_pdb
|
__init__
| null |
def __init__(self, host, port, patch_stdstreams=False, quiet=False):
self._quiet = quiet
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
listen_socket.bind((host, port))
if not self._quiet:
cry("RemotePdb session open at %s:%s, waiting for connection ..." % listen_socket.getsockname())
listen_socket.listen(1)
connection, address = listen_socket.accept()
if not self._quiet:
cry("RemotePdb accepted connection from %s." % repr(address))
self.handle = LF2CRLF_FileWrapper(connection)
Pdb.__init__(self, completekey='tab', stdin=self.handle, stdout=self.handle)
self.backup = []
if patch_stdstreams:
for name in (
'stderr',
'stdout',
'__stderr__',
'__stdout__',
'stdin',
'__stdin__',
):
self.backup.append((name, getattr(sys, name)))
setattr(sys, name, self.handle)
RemotePdb.active_instance = self
|
(self, host, port, patch_stdstreams=False, quiet=False)
|
706,848
|
remote_pdb
|
do_quit
| null |
def do_quit(self, arg):
self.__restore()
return Pdb.do_quit(self, arg)
|
(self, arg)
|
706,924
|
remote_pdb
|
set_trace
| null |
def set_trace(self, frame=None):
if frame is None:
frame = sys._getframe().f_back
try:
Pdb.set_trace(self, frame)
except IOError as exc:
if exc.errno != errno.ECONNRESET:
raise
|
(self, frame=None)
|
706,934
|
remote_pdb
|
cry
| null |
def cry(message, stderr=sys.__stderr__):
log.critical(message)
print(message, file=stderr)
stderr.flush()
|
(message, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>)
|
706,939
|
remote_pdb
|
set_trace
|
Opens a remote PDB on first available port.
|
def set_trace(host=None, port=None, patch_stdstreams=False, quiet=None):
"""
Opens a remote PDB on first available port.
"""
if host is None:
host = os.environ.get('REMOTE_PDB_HOST', '127.0.0.1')
if port is None:
port = int(os.environ.get('REMOTE_PDB_PORT', '0'))
if quiet is None:
quiet = bool(os.environ.get('REMOTE_PDB_QUIET', ''))
rdb = RemotePdb(host=host, port=port, patch_stdstreams=patch_stdstreams, quiet=quiet)
rdb.set_trace(frame=sys._getframe().f_back)
|
(host=None, port=None, patch_stdstreams=False, quiet=None)
|
706,990
|
pybind11_stubgen.parser.mixins.parse
|
BaseParser
| null |
class BaseParser(IParser):
def handle_alias(self, path: QualifiedName, origin: Any) -> Alias | None:
full_name = self._get_full_name(path, origin)
if full_name is None:
return None
return Alias(
name=path[-1],
origin=full_name,
)
def handle_attribute(self, path: QualifiedName, value: Any) -> Attribute | None:
return Attribute(
name=path[-1],
value=self.handle_value(value),
annotation=ResolvedType(name=self.handle_type(type(value))),
)
def handle_bases(
self, path: QualifiedName, bases: tuple[type, ...]
) -> list[QualifiedName]:
return [self.handle_type(type_) for type_ in bases if type_ is not object]
def handle_docstring(self, path: QualifiedName, value: Any) -> Docstring | None:
if isinstance(value, str):
return Docstring(value)
return None
def handle_field(self, path: QualifiedName, value: Any) -> Field | None:
attr = self.handle_attribute(path, value)
if attr is None:
return None
result = Field(
attribute=Attribute(
name=attr.name,
value=attr.value,
),
modifier="static",
)
if attr.annotation is not None:
class_var = self.parse_annotation_str("typing.ClassVar")
assert isinstance(class_var, ResolvedType)
result.attribute.annotation = ResolvedType(
name=class_var.name,
parameters=[attr.annotation],
)
return result
def handle_function(self, path: QualifiedName, func: Any) -> list[Function]:
doc: Docstring | None = (
Docstring(func.__doc__)
if getattr(func, "__doc__", None) is not None
else None
)
func_name = Identifier(path[-1])
try:
(
args,
var_args,
var_kw,
defaults,
kw_only_args,
kw_only_defaults,
annotations,
) = inspect.getfullargspec(func)
func_args: dict[str, Argument] = {
arg_name: Argument(name=Identifier(arg_name)) for arg_name in args
}
func_args["return"] = Argument(
name=Identifier(),
)
if var_args is not None:
func_args[var_args] = Argument(name=Identifier(var_args), variadic=True)
for arg_name in kw_only_args:
func_args[arg_name] = Argument(name=Identifier(arg_name), kw_only=True)
if var_kw is not None:
func_args[var_kw] = Argument(name=Identifier(var_kw), kw_variadic=True)
if defaults is not None:
for i, default in enumerate(defaults):
arg_name = args[len(args) - len(defaults) + i]
func_args[arg_name].default = self.handle_value(default)
if kw_only_defaults is not None:
for arg_name, default in kw_only_defaults.items():
func_args[arg_name].default = self.handle_value(default)
for arg_name, annotation in annotations.items():
if isinstance(annotation, str):
func_args[arg_name].annotation = self.parse_annotation_str(
annotation
)
elif not isinstance(annotation, type):
func_args[arg_name].annotation = self.handle_value(annotation)
elif self._is_generic_alias(annotation):
func_args[arg_name].annotation = self.parse_annotation_str(
str(annotation)
)
else:
func_args[arg_name].annotation = ResolvedType(
name=self.handle_type(annotation),
)
if "return" in func_args:
returns = func_args["return"].annotation
else:
returns = None
return [
Function(
name=func_name,
args=[
arg
for arg_name, arg in func_args.items()
if arg_name != "return"
],
returns=returns,
doc=doc,
)
]
except TypeError:
# generic signature `f(*args, *kwargs)`
return [
Function(
name=func_name,
args=_generic_args,
doc=doc,
)
]
def _is_generic_alias(self, annotation: type) -> bool:
generic_alias_t: type | None = getattr(types, "GenericAlias", None)
if generic_alias_t is None:
return False
return isinstance(annotation, generic_alias_t)
def handle_import(self, path: QualifiedName, origin: Any) -> Import | None:
full_name = self._get_full_name(path, origin)
if full_name is None:
return None
return Import(
path[-1],
full_name,
)
def handle_method(self, path: QualifiedName, method: Any) -> list[Method]:
return [
Method(function=func, modifier=self._get_method_modifier(func.args))
for func in self.handle_function(path, method)
]
def handle_value(self, value: Any) -> Value:
value_type = type(value)
# Use exact type match, not `isinstance()` that allows inherited types pass
if value is None or value_type in (bool, int, str):
return Value(repr=repr(value), is_print_safe=True)
if value_type in (float, complex):
try:
# checks for NaN, +inf, -inf
repr_str = repr(value)
eval(repr_str)
return Value(repr=repr_str, is_print_safe=True)
except (SyntaxError, NameError):
pass
if value_type in (list, tuple, set):
assert isinstance(value, (list, tuple, set))
if len(value) == 0:
return Value(repr=f"{value_type.__name__}()", is_print_safe=True)
elements: list[Value] = [self.handle_value(el) for el in value]
is_print_safe = all(el.is_print_safe for el in elements)
left, right = {
list: "[]",
tuple: "()",
set: "{}",
}[value_type]
return Value(
repr="".join([left, ", ".join(el.repr for el in elements), right]),
is_print_safe=is_print_safe,
)
if value_type is dict:
assert isinstance(value, dict)
parts = []
is_print_safe = True
for k, v in value.items():
k_value = self.handle_value(k)
v_value = self.handle_value(v)
parts.append(f"{k_value.repr}: {v_value.repr}")
is_print_safe = (
is_print_safe and k_value.is_print_safe and v_value.is_print_safe
)
return Value(
repr="".join(["{", ", ".join(parts), "}"]), is_print_safe=is_print_safe
)
if inspect.isroutine(value):
module_name = getattr(value, "__module__", None)
qual_name = getattr(value, "__qualname__", None)
if (
module_name is not None
and "<" not in module_name
and qual_name is not None
and "<" not in qual_name
):
if module_name == "builtins":
repr_str = qual_name
else:
repr_str = f"{module_name}.{qual_name}"
return Value(repr=repr_str, is_print_safe=True)
if inspect.isclass(value):
return Value(repr=str(self.handle_type(value)), is_print_safe=True)
if inspect.ismodule(value):
return Value(repr=value.__name__, is_print_safe=True)
return Value(repr=repr(value), is_print_safe=False)
def handle_type(self, type_: type) -> QualifiedName:
return QualifiedName(
(
Identifier(part)
for part in (
*type_.__module__.split("."),
*type_.__qualname__.split("."),
)
)
)
def parse_value_str(self, value: str) -> Value | InvalidExpression:
return self._parse_expression_str(value)
def report_error(self, error: ParserError):
if isinstance(error, NameResolutionError):
if error.name[0] == "module":
return
super().report_error(error)
def _get_method_modifier(self, args: list[Argument]) -> Modifier:
if len(args) == 0:
return "static"
name = args[0].name
if name == Identifier("self"):
return None
elif name == Identifier("cls"):
return "class"
else:
return "static"
def _get_full_name(self, path: QualifiedName, origin: Any) -> QualifiedName | None:
if inspect.ismodule(origin):
origin_full_name = origin.__name__
else:
module_name = getattr(origin, "__module__", None)
if module_name == "__future__":
return None
if module_name is None:
self.report_error(NameResolutionError(path))
return None
qual_name = getattr(origin, "__qualname__", None)
if qual_name is None:
self.report_error(NameResolutionError(path))
return None
# Note: `PyCapsule.` prefix in __qualname__ is an artefact of pybind11
_PyCapsule = "PyCapsule."
if qual_name.startswith(_PyCapsule):
qual_name = qual_name[len(_PyCapsule) :]
origin_full_name = f"{module_name}.{qual_name}"
origin_name = QualifiedName.from_str(origin_full_name)
for part in origin_name:
if not part.isidentifier():
self.report_error(InvalidIdentifierError(part, path))
return None
return origin_name
def _parse_expression_str(self, expr_str: str) -> Value | InvalidExpression:
strip_expr = expr_str.strip()
try:
ast.parse(strip_expr)
print_safe = False
try:
ast.literal_eval(strip_expr)
print_safe = True
except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
pass
return Value(strip_expr, is_print_safe=print_safe)
except SyntaxError:
self.report_error(InvalidExpressionError(strip_expr))
return InvalidExpression(strip_expr)
|
()
|
706,991
|
pybind11_stubgen.parser.mixins.parse
|
_get_full_name
| null |
def _get_full_name(self, path: QualifiedName, origin: Any) -> QualifiedName | None:
if inspect.ismodule(origin):
origin_full_name = origin.__name__
else:
module_name = getattr(origin, "__module__", None)
if module_name == "__future__":
return None
if module_name is None:
self.report_error(NameResolutionError(path))
return None
qual_name = getattr(origin, "__qualname__", None)
if qual_name is None:
self.report_error(NameResolutionError(path))
return None
# Note: `PyCapsule.` prefix in __qualname__ is an artefact of pybind11
_PyCapsule = "PyCapsule."
if qual_name.startswith(_PyCapsule):
qual_name = qual_name[len(_PyCapsule) :]
origin_full_name = f"{module_name}.{qual_name}"
origin_name = QualifiedName.from_str(origin_full_name)
for part in origin_name:
if not part.isidentifier():
self.report_error(InvalidIdentifierError(part, path))
return None
return origin_name
|
(self, path: pybind11_stubgen.structs.QualifiedName, origin: Any) -> pybind11_stubgen.structs.QualifiedName | None
|
706,992
|
pybind11_stubgen.parser.mixins.parse
|
_get_method_modifier
| null |
def _get_method_modifier(self, args: list[Argument]) -> Modifier:
if len(args) == 0:
return "static"
name = args[0].name
if name == Identifier("self"):
return None
elif name == Identifier("cls"):
return "class"
else:
return "static"
|
(self, args: list[pybind11_stubgen.structs.Argument]) -> Literal['static', 'class', None]
|
706,993
|
pybind11_stubgen.parser.mixins.parse
|
_is_generic_alias
| null |
def _is_generic_alias(self, annotation: type) -> bool:
generic_alias_t: type | None = getattr(types, "GenericAlias", None)
if generic_alias_t is None:
return False
return isinstance(annotation, generic_alias_t)
|
(self, annotation: type) -> bool
|
706,994
|
pybind11_stubgen.parser.mixins.parse
|
_parse_expression_str
| null |
def _parse_expression_str(self, expr_str: str) -> Value | InvalidExpression:
strip_expr = expr_str.strip()
try:
ast.parse(strip_expr)
print_safe = False
try:
ast.literal_eval(strip_expr)
print_safe = True
except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
pass
return Value(strip_expr, is_print_safe=print_safe)
except SyntaxError:
self.report_error(InvalidExpressionError(strip_expr))
return InvalidExpression(strip_expr)
|
(self, expr_str: str) -> pybind11_stubgen.structs.Value | pybind11_stubgen.structs.InvalidExpression
|
706,995
|
pybind11_stubgen.parser.interface
|
finalize
| null |
@abc.abstractmethod
def finalize(self):
...
|
(self)
|
706,996
|
pybind11_stubgen.parser.mixins.parse
|
handle_alias
| null |
def handle_alias(self, path: QualifiedName, origin: Any) -> Alias | None:
full_name = self._get_full_name(path, origin)
if full_name is None:
return None
return Alias(
name=path[-1],
origin=full_name,
)
|
(self, path: pybind11_stubgen.structs.QualifiedName, origin: Any) -> pybind11_stubgen.structs.Alias | None
|
706,997
|
pybind11_stubgen.parser.mixins.parse
|
handle_attribute
| null |
def handle_attribute(self, path: QualifiedName, value: Any) -> Attribute | None:
return Attribute(
name=path[-1],
value=self.handle_value(value),
annotation=ResolvedType(name=self.handle_type(type(value))),
)
|
(self, path: pybind11_stubgen.structs.QualifiedName, value: Any) -> pybind11_stubgen.structs.Attribute | None
|
706,998
|
pybind11_stubgen.parser.mixins.parse
|
handle_bases
| null |
def handle_bases(
self, path: QualifiedName, bases: tuple[type, ...]
) -> list[QualifiedName]:
return [self.handle_type(type_) for type_ in bases if type_ is not object]
|
(self, path: pybind11_stubgen.structs.QualifiedName, bases: tuple[type, ...]) -> list[pybind11_stubgen.structs.QualifiedName]
|
706,999
|
pybind11_stubgen.parser.interface
|
handle_class
| null |
@abc.abstractmethod
def handle_class(self, path: QualifiedName, class_: type) -> Class | None:
...
|
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type) -> pybind11_stubgen.structs.Class | None
|
707,000
|
pybind11_stubgen.parser.interface
|
handle_class_member
| null |
@abc.abstractmethod
def handle_class_member(
self, path: QualifiedName, class_: type, obj: Any
) -> Docstring | Alias | Class | list[Method] | Field | Property | None:
...
|
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type, obj: Any) -> pybind11_stubgen.structs.Docstring | pybind11_stubgen.structs.Alias | pybind11_stubgen.structs.Class | list[pybind11_stubgen.structs.Method] | pybind11_stubgen.structs.Field | pybind11_stubgen.structs.Property | None
|
707,001
|
pybind11_stubgen.parser.mixins.parse
|
handle_docstring
| null |
def handle_docstring(self, path: QualifiedName, value: Any) -> Docstring | None:
if isinstance(value, str):
return Docstring(value)
return None
|
(self, path: pybind11_stubgen.structs.QualifiedName, value: Any) -> pybind11_stubgen.structs.Docstring | None
|
707,002
|
pybind11_stubgen.parser.mixins.parse
|
handle_field
| null |
def handle_field(self, path: QualifiedName, value: Any) -> Field | None:
attr = self.handle_attribute(path, value)
if attr is None:
return None
result = Field(
attribute=Attribute(
name=attr.name,
value=attr.value,
),
modifier="static",
)
if attr.annotation is not None:
class_var = self.parse_annotation_str("typing.ClassVar")
assert isinstance(class_var, ResolvedType)
result.attribute.annotation = ResolvedType(
name=class_var.name,
parameters=[attr.annotation],
)
return result
|
(self, path: pybind11_stubgen.structs.QualifiedName, value: Any) -> pybind11_stubgen.structs.Field | None
|
707,003
|
pybind11_stubgen.parser.mixins.parse
|
handle_function
| null |
def handle_function(self, path: QualifiedName, func: Any) -> list[Function]:
doc: Docstring | None = (
Docstring(func.__doc__)
if getattr(func, "__doc__", None) is not None
else None
)
func_name = Identifier(path[-1])
try:
(
args,
var_args,
var_kw,
defaults,
kw_only_args,
kw_only_defaults,
annotations,
) = inspect.getfullargspec(func)
func_args: dict[str, Argument] = {
arg_name: Argument(name=Identifier(arg_name)) for arg_name in args
}
func_args["return"] = Argument(
name=Identifier(),
)
if var_args is not None:
func_args[var_args] = Argument(name=Identifier(var_args), variadic=True)
for arg_name in kw_only_args:
func_args[arg_name] = Argument(name=Identifier(arg_name), kw_only=True)
if var_kw is not None:
func_args[var_kw] = Argument(name=Identifier(var_kw), kw_variadic=True)
if defaults is not None:
for i, default in enumerate(defaults):
arg_name = args[len(args) - len(defaults) + i]
func_args[arg_name].default = self.handle_value(default)
if kw_only_defaults is not None:
for arg_name, default in kw_only_defaults.items():
func_args[arg_name].default = self.handle_value(default)
for arg_name, annotation in annotations.items():
if isinstance(annotation, str):
func_args[arg_name].annotation = self.parse_annotation_str(
annotation
)
elif not isinstance(annotation, type):
func_args[arg_name].annotation = self.handle_value(annotation)
elif self._is_generic_alias(annotation):
func_args[arg_name].annotation = self.parse_annotation_str(
str(annotation)
)
else:
func_args[arg_name].annotation = ResolvedType(
name=self.handle_type(annotation),
)
if "return" in func_args:
returns = func_args["return"].annotation
else:
returns = None
return [
Function(
name=func_name,
args=[
arg
for arg_name, arg in func_args.items()
if arg_name != "return"
],
returns=returns,
doc=doc,
)
]
except TypeError:
# generic signature `f(*args, *kwargs)`
return [
Function(
name=func_name,
args=_generic_args,
doc=doc,
)
]
|
(self, path: pybind11_stubgen.structs.QualifiedName, func: Any) -> list[pybind11_stubgen.structs.Function]
|
707,004
|
pybind11_stubgen.parser.mixins.parse
|
handle_import
| null |
def handle_import(self, path: QualifiedName, origin: Any) -> Import | None:
full_name = self._get_full_name(path, origin)
if full_name is None:
return None
return Import(
path[-1],
full_name,
)
|
(self, path: pybind11_stubgen.structs.QualifiedName, origin: Any) -> pybind11_stubgen.structs.Import | None
|
707,005
|
pybind11_stubgen.parser.mixins.parse
|
handle_method
| null |
def handle_method(self, path: QualifiedName, method: Any) -> list[Method]:
return [
Method(function=func, modifier=self._get_method_modifier(func.args))
for func in self.handle_function(path, method)
]
|
(self, path: pybind11_stubgen.structs.QualifiedName, method: Any) -> list[pybind11_stubgen.structs.Method]
|
707,006
|
pybind11_stubgen.parser.interface
|
handle_module
| null |
@abc.abstractmethod
def handle_module(
self, path: QualifiedName, module: types.ModuleType
) -> Module | None:
...
|
(self, path: pybind11_stubgen.structs.QualifiedName, module: module) -> pybind11_stubgen.structs.Module | None
|
707,007
|
pybind11_stubgen.parser.interface
|
handle_module_member
| null |
@abc.abstractmethod
def handle_module_member(
self, path: QualifiedName, module: types.ModuleType, obj: Any
) -> (
Docstring | Import | Alias | Class | list[Function] | Attribute | Module | None
):
...
|
(self, path: pybind11_stubgen.structs.QualifiedName, module: module, obj: Any) -> pybind11_stubgen.structs.Docstring | pybind11_stubgen.structs.Import | pybind11_stubgen.structs.Alias | pybind11_stubgen.structs.Class | list[pybind11_stubgen.structs.Function] | pybind11_stubgen.structs.Attribute | pybind11_stubgen.structs.Module | None
|
707,008
|
pybind11_stubgen.parser.interface
|
handle_property
| null |
@abc.abstractmethod
def handle_property(self, path: QualifiedName, prop: Any) -> Property | None:
...
|
(self, path: pybind11_stubgen.structs.QualifiedName, prop: Any) -> pybind11_stubgen.structs.Property | None
|
707,009
|
pybind11_stubgen.parser.mixins.parse
|
handle_type
| null |
def handle_type(self, type_: type) -> QualifiedName:
return QualifiedName(
(
Identifier(part)
for part in (
*type_.__module__.split("."),
*type_.__qualname__.split("."),
)
)
)
|
(self, type_: type) -> pybind11_stubgen.structs.QualifiedName
|
707,010
|
pybind11_stubgen.parser.mixins.parse
|
handle_value
| null |
def handle_value(self, value: Any) -> Value:
value_type = type(value)
# Use exact type match, not `isinstance()` that allows inherited types pass
if value is None or value_type in (bool, int, str):
return Value(repr=repr(value), is_print_safe=True)
if value_type in (float, complex):
try:
# checks for NaN, +inf, -inf
repr_str = repr(value)
eval(repr_str)
return Value(repr=repr_str, is_print_safe=True)
except (SyntaxError, NameError):
pass
if value_type in (list, tuple, set):
assert isinstance(value, (list, tuple, set))
if len(value) == 0:
return Value(repr=f"{value_type.__name__}()", is_print_safe=True)
elements: list[Value] = [self.handle_value(el) for el in value]
is_print_safe = all(el.is_print_safe for el in elements)
left, right = {
list: "[]",
tuple: "()",
set: "{}",
}[value_type]
return Value(
repr="".join([left, ", ".join(el.repr for el in elements), right]),
is_print_safe=is_print_safe,
)
if value_type is dict:
assert isinstance(value, dict)
parts = []
is_print_safe = True
for k, v in value.items():
k_value = self.handle_value(k)
v_value = self.handle_value(v)
parts.append(f"{k_value.repr}: {v_value.repr}")
is_print_safe = (
is_print_safe and k_value.is_print_safe and v_value.is_print_safe
)
return Value(
repr="".join(["{", ", ".join(parts), "}"]), is_print_safe=is_print_safe
)
if inspect.isroutine(value):
module_name = getattr(value, "__module__", None)
qual_name = getattr(value, "__qualname__", None)
if (
module_name is not None
and "<" not in module_name
and qual_name is not None
and "<" not in qual_name
):
if module_name == "builtins":
repr_str = qual_name
else:
repr_str = f"{module_name}.{qual_name}"
return Value(repr=repr_str, is_print_safe=True)
if inspect.isclass(value):
return Value(repr=str(self.handle_type(value)), is_print_safe=True)
if inspect.ismodule(value):
return Value(repr=value.__name__, is_print_safe=True)
return Value(repr=repr(value), is_print_safe=False)
|
(self, value: Any) -> pybind11_stubgen.structs.Value
|
707,011
|
pybind11_stubgen.parser.interface
|
parse_annotation_str
| null |
@abc.abstractmethod
def parse_annotation_str(
self, annotation_str: str
) -> ResolvedType | InvalidExpression | Value:
...
|
(self, annotation_str: str) -> pybind11_stubgen.structs.ResolvedType | pybind11_stubgen.structs.InvalidExpression | pybind11_stubgen.structs.Value
|
707,012
|
pybind11_stubgen.parser.interface
|
parse_args_str
| null |
@abc.abstractmethod
def parse_args_str(self, args_str: str) -> list[Argument]:
...
|
(self, args_str: str) -> list[pybind11_stubgen.structs.Argument]
|
707,013
|
pybind11_stubgen.parser.mixins.parse
|
parse_value_str
| null |
def parse_value_str(self, value: str) -> Value | InvalidExpression:
return self._parse_expression_str(value)
|
(self, value: str) -> pybind11_stubgen.structs.Value | pybind11_stubgen.structs.InvalidExpression
|
707,014
|
pybind11_stubgen.parser.mixins.parse
|
report_error
| null |
def report_error(self, error: ParserError):
if isinstance(error, NameResolutionError):
if error.name[0] == "module":
return
super().report_error(error)
|
(self, error: pybind11_stubgen.parser.errors.ParserError)
|
707,015
|
pybind11_stubgen
|
CLIArgs
| null |
class CLIArgs(Namespace):
output_dir: str
root_suffix: str
ignore_invalid_expressions: re.Pattern | None
ignore_invalid_identifiers: re.Pattern | None
ignore_unresolved_names: re.Pattern | None
ignore_all_errors: bool
enum_class_locations: list[tuple[re.Pattern, str]]
numpy_array_wrap_with_annotated: bool
numpy_array_use_type_var: bool
numpy_array_remove_parameters: bool
print_invalid_expressions_as_is: bool
print_safe_value_reprs: re.Pattern | None
exit_code: bool
dry_run: bool
stub_extension: str
module_name: str
|
(**kwargs)
|
707,022
|
pybind11_stubgen.parser.mixins.parse
|
ExtractSignaturesFromPybind11Docstrings
| null |
class ExtractSignaturesFromPybind11Docstrings(IParser):
_arg_star_name_regex = re.compile(
r"^\s*(?P<stars>\*{1,2})?" r"\s*(?P<name>\w+)\s*$"
)
def handle_function(self, path: QualifiedName, func: Any) -> list[Function]:
result = super().handle_function(path, func)
if len(result) == 1 and result[0].args == _generic_args:
doc: str | None = func.__doc__
func_name = Identifier(path[-1])
if doc is not None:
parsed_funcs = self.parse_function_docstring(
func_name, doc.splitlines()
)
if len(parsed_funcs) > 0:
return parsed_funcs
return result
def handle_property(self, path: QualifiedName, prop: Any) -> Property | None:
result = Property(name=path[-1], modifier=None)
# Note: pybind *usually* does not include function name
# in getter/setter signatures, e.g.:
# (arg0: demo._bindings.enum.ConsoleForegroundColor) -> int
#
fake_path = QualifiedName((*path, Identifier("")))
if hasattr(prop, "fget") and prop.fget is not None:
for func_path in [fake_path, path]:
result.getter = self._fixup_parsed_getters_or_setters(
self.handle_function(func_path, prop.fget)
)
if result.getter is not None and result.getter.args != _generic_args:
break
if hasattr(prop, "fset") and prop.fset is not None:
for func_path in [fake_path, path]:
result.setter = self._fixup_parsed_getters_or_setters(
self.handle_function(func_path, prop.fset)
)
if result.setter is not None and result.setter.args != _generic_args:
break
if result.getter is None and result.setter is None:
return None
prop_doc = getattr(prop, "__doc__", None)
if prop_doc is not None:
result.doc = self._strip_empty_lines(prop_doc.splitlines())
if (
result.doc is not None
and result.getter is not None
and (
result.doc == result.getter.doc
or result.doc
== self._strip_empty_lines(
(getattr(prop.fget, "__doc__", "") or "").splitlines()
)
)
):
result.doc = None
return result
def parse_args_str(self, args_str: str) -> list[Argument]:
split_args = self._split_args_str(args_str)
if split_args is None:
return _generic_args
result: list[Argument] = []
kw_only = False
for arg_str, annotation_str, default_str in split_args:
if arg_str.strip() == "/":
for arg in result:
arg.pos_only = True
continue
if arg_str.strip() == "*":
kw_only = True
continue
match = self._arg_star_name_regex.match(arg_str)
if match is None:
return _generic_args
name = Identifier(match.group("name"))
variadic = False
kw_variadic = False
stars = match.group("stars")
if stars == "*":
variadic = True
elif stars == "**":
kw_variadic = True
if annotation_str is not None:
annotation = self.parse_annotation_str(annotation_str)
else:
annotation = None
if default_str is not None:
default = self.parse_value_str(default_str)
else:
default = None
result.append(
Argument(
name=name,
default=default,
annotation=annotation,
variadic=variadic,
kw_variadic=kw_variadic,
kw_only=kw_only,
)
)
return result
def parse_annotation_str(
self, annotation_str: str
) -> ResolvedType | InvalidExpression | Value:
variants = self._split_type_union_str(annotation_str)
if variants is None or len(variants) == 0:
self.report_error(InvalidExpressionError(annotation_str))
return InvalidExpression(annotation_str)
if len(variants) == 1:
return self.parse_type_str(variants[0])
union_t = self.parse_annotation_str("typing.Union")
assert isinstance(union_t, ResolvedType)
return ResolvedType(
name=union_t.name,
parameters=[self.parse_type_str(variant) for variant in variants],
)
def parse_type_str(
self, annotation_str: str
) -> ResolvedType | InvalidExpression | Value:
qname_regex = re.compile(
r"^\s*(?P<qual_name>([_A-Za-z]\w*)?(\s*\.\s*[_A-Za-z]\w*)*)"
)
annotation_str = annotation_str.strip()
match = qname_regex.match(annotation_str)
if match is None:
return self.parse_value_str(annotation_str)
qual_name = QualifiedName(
Identifier(part)
for part in match.group("qual_name").replace(" ", "").split(".")
)
parameters_str = annotation_str[match.end("qual_name") :].strip()
if len(parameters_str) == 0:
parameters = None
else:
if parameters_str[0] != "[" or parameters_str[-1] != "]":
return self.parse_value_str(annotation_str)
split_parameters = self._split_parameters_str(parameters_str[1:-1])
if split_parameters is None:
return self.parse_value_str(annotation_str)
parameters = [
self.parse_annotation_str(param_str) for param_str in split_parameters
]
return ResolvedType(name=qual_name, parameters=parameters)
def parse_function_docstring(
self, func_name: Identifier, doc_lines: list[str]
) -> list[Function]:
if len(doc_lines) == 0:
return []
top_signature_regex = re.compile(
rf"^{func_name}\((?P<args>.*)\)\s*(->\s*(?P<returns>.+))?$"
)
match = top_signature_regex.match(doc_lines[0])
if match is None:
return []
if len(doc_lines) < 2 or doc_lines[1] != "Overloaded function.":
returns_str = match.group("returns")
if returns_str is not None:
returns = self.parse_annotation_str(returns_str)
else:
returns = None
return [
Function(
name=func_name,
args=self.parse_args_str(match.group("args")),
doc=self._strip_empty_lines(doc_lines[1:]),
returns=returns,
)
]
overload_signature_regex = re.compile(
rf"^(\s*(?P<overload_number>\d+).\s*)"
rf"{func_name}\((?P<args>.*)\)\s*->\s*(?P<returns>.+)$"
)
doc_start = 0
_dummy = Function(Identifier(""))
overloads = [_dummy]
for i in range(2, len(doc_lines)):
match = overload_signature_regex.match(doc_lines[i])
if match:
if match.group("overload_number") != f"{len(overloads)}":
continue
overloads[-1].doc = self._strip_empty_lines(doc_lines[doc_start:i])
doc_start = i + 1
overloads.append(
Function(
name=func_name,
args=self.parse_args_str(match.group("args")),
returns=self.parse_annotation_str(match.group("returns")),
doc=None,
decorators=[
# use `parse_annotation_str()` to trigger typing import
Decorator(str(self.parse_annotation_str("typing.overload")))
],
)
)
overloads[-1].doc = self._strip_empty_lines(doc_lines[doc_start:])
return overloads[1:]
def _fixup_parsed_getters_or_setters(
self, funcs: list[Function]
) -> Function | None:
if len(funcs) == 0:
return None
if len(funcs) > 1:
raise RuntimeError(
"Multiple overloads in property's getters/setters are not supported"
)
func = funcs[0]
if (
len(func.args) > 0
and not func.args[0].variadic
and not func.args[0].kw_variadic
and func.args[0].default is None
):
func.args[0].name = Identifier("self")
func.args[0].annotation = None
else:
pass
# TODO: produce warning
return func
def _split_args_str(
self, args_str: str
) -> list[tuple[str, str | None, str | None]] | None:
result = []
closing = {"(": ")", "{": "}", "[": "]"}
stack = []
i = 0
arg_begin = 0
semicolon_pos: int | None = None
eq_sign_pos: int | None = None
def add_arg():
nonlocal semicolon_pos
nonlocal eq_sign_pos
annotation = None
default = None
arg_end = i
if eq_sign_pos is not None:
arg_end = eq_sign_pos
default = args_str[eq_sign_pos + 1 : i]
if semicolon_pos is not None:
annotation = args_str[semicolon_pos + 1 : arg_end]
arg_end = semicolon_pos
name = args_str[arg_begin:arg_end]
result.append((name, annotation, default))
semicolon_pos = None
eq_sign_pos = None
while i < len(args_str):
c = args_str[i]
if c in "\"'":
# TODO: handle triple-quoted strings too
str_end = self._find_str_end(args_str, i)
if str_end is None:
return None
i = str_end
elif c in closing:
stack.append(closing[c])
elif len(stack) == 0:
if c == ",":
add_arg()
arg_begin = i + 1
elif c == ":" and semicolon_pos is None:
semicolon_pos = i
elif c == "=" and args_str[i : i + 2] != "==":
eq_sign_pos = i
elif stack[-1] == c:
stack.pop()
i += 1
if len(stack) != 0:
return None
if len(args_str[arg_begin:i].strip()) != 0:
add_arg()
return result
def _split_type_union_str(self, type_str: str) -> list[str] | None:
return self._split_str(type_str, delim="|")
def _split_parameters_str(self, param_str: str) -> list[str] | None:
return self._split_str(param_str, delim=",")
def _split_str(self, param_str: str, delim: str):
result = []
closing = {"(": ")", "{": "}", "[": "]"}
stack = []
i = 0
arg_begin = 0
def add_arg():
arg_end = i
param = param_str[arg_begin:arg_end]
result.append(param)
while i < len(param_str):
c = param_str[i]
if c in "\"'":
# TODO: handle triple-quoted strings too
str_end = self._find_str_end(param_str, i)
if str_end is None:
return None
i = str_end
elif c in closing:
stack.append(closing[c])
elif len(stack) == 0:
if c == delim:
add_arg()
arg_begin = i + 1
elif stack[-1] == c:
stack.pop()
i += 1
if len(stack) != 0:
return None
if param_str[arg_begin:i].strip() != 0:
add_arg()
return result
def _find_str_end(self, s, start) -> int | None:
for i in range(start + 1, len(s)):
c = s[i]
if c == "\\": # skip escaped chars
continue
if c == s[start]:
return i
return None
def _strip_empty_lines(self, doc_lines: list[str]) -> Docstring | None:
assert isinstance(doc_lines, list)
start = 0
for start in range(0, len(doc_lines)):
if len(doc_lines[start].strip()) > 0:
break
end = len(doc_lines) - 1
for end in range(len(doc_lines) - 1, 0, -1):
if len(doc_lines[end].strip()) > 0:
break
result = "\n".join(doc_lines[start : end + 1])
if len(result) == 0:
return None
return Docstring(result)
def report_error(self, error: ParserError) -> None:
if isinstance(error, NameResolutionError):
if error.name[0] == "pybind11_builtins":
return
if isinstance(error, InvalidIdentifierError):
name = error.name
if (
name.startswith("ItemsView[")
and name.endswith("]")
or name.startswith("KeysView[")
and name.endswith("]")
or name.startswith("ValuesView[")
and name.endswith("]")
):
return
super().report_error(error)
def handle_bases(
self, path: QualifiedName, bases: tuple[type, ...]
) -> list[QualifiedName]:
result = []
for base in super().handle_bases(path, bases):
if base[0] == "pybind11_builtins":
break
result.append(base)
return result
|
()
|
707,023
|
pybind11_stubgen.parser.mixins.parse
|
_find_str_end
| null |
def _find_str_end(self, s, start) -> int | None:
for i in range(start + 1, len(s)):
c = s[i]
if c == "\\": # skip escaped chars
continue
if c == s[start]:
return i
return None
|
(self, s, start) -> int | None
|
707,024
|
pybind11_stubgen.parser.mixins.parse
|
_fixup_parsed_getters_or_setters
| null |
def _fixup_parsed_getters_or_setters(
self, funcs: list[Function]
) -> Function | None:
if len(funcs) == 0:
return None
if len(funcs) > 1:
raise RuntimeError(
"Multiple overloads in property's getters/setters are not supported"
)
func = funcs[0]
if (
len(func.args) > 0
and not func.args[0].variadic
and not func.args[0].kw_variadic
and func.args[0].default is None
):
func.args[0].name = Identifier("self")
func.args[0].annotation = None
else:
pass
# TODO: produce warning
return func
|
(self, funcs: list[pybind11_stubgen.structs.Function]) -> pybind11_stubgen.structs.Function | None
|
707,025
|
pybind11_stubgen.parser.mixins.parse
|
_split_args_str
| null |
def _split_args_str(
self, args_str: str
) -> list[tuple[str, str | None, str | None]] | None:
result = []
closing = {"(": ")", "{": "}", "[": "]"}
stack = []
i = 0
arg_begin = 0
semicolon_pos: int | None = None
eq_sign_pos: int | None = None
def add_arg():
nonlocal semicolon_pos
nonlocal eq_sign_pos
annotation = None
default = None
arg_end = i
if eq_sign_pos is not None:
arg_end = eq_sign_pos
default = args_str[eq_sign_pos + 1 : i]
if semicolon_pos is not None:
annotation = args_str[semicolon_pos + 1 : arg_end]
arg_end = semicolon_pos
name = args_str[arg_begin:arg_end]
result.append((name, annotation, default))
semicolon_pos = None
eq_sign_pos = None
while i < len(args_str):
c = args_str[i]
if c in "\"'":
# TODO: handle triple-quoted strings too
str_end = self._find_str_end(args_str, i)
if str_end is None:
return None
i = str_end
elif c in closing:
stack.append(closing[c])
elif len(stack) == 0:
if c == ",":
add_arg()
arg_begin = i + 1
elif c == ":" and semicolon_pos is None:
semicolon_pos = i
elif c == "=" and args_str[i : i + 2] != "==":
eq_sign_pos = i
elif stack[-1] == c:
stack.pop()
i += 1
if len(stack) != 0:
return None
if len(args_str[arg_begin:i].strip()) != 0:
add_arg()
return result
|
(self, args_str: str) -> list[tuple[str, str | None, str | None]] | None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.