repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
pygobject/pgi
pgi/overrides/Gtk.py
TreeSelection.get_selected_rows
def get_selected_rows(self): """ :returns: A list containing a :obj:`Gtk.TreePath` for each selected row and a :obj:`Gtk.TreeModel` or :obj:`None`. :rtype: (:obj:`Gtk.TreeModel`, [:obj:`Gtk.TreePath`]) {{ docs }} """ rows, model = super(TreeSelection, self).get_selected_rows() return (model, rows)
python
def get_selected_rows(self): """ :returns: A list containing a :obj:`Gtk.TreePath` for each selected row and a :obj:`Gtk.TreeModel` or :obj:`None`. :rtype: (:obj:`Gtk.TreeModel`, [:obj:`Gtk.TreePath`]) {{ docs }} """ rows, model = super(TreeSelection, self).get_selected_rows() return (model, rows)
[ "def", "get_selected_rows", "(", "self", ")", ":", "rows", ",", "model", "=", "super", "(", "TreeSelection", ",", "self", ")", ".", "get_selected_rows", "(", ")", "return", "(", "model", ",", "rows", ")" ]
:returns: A list containing a :obj:`Gtk.TreePath` for each selected row and a :obj:`Gtk.TreeModel` or :obj:`None`. :rtype: (:obj:`Gtk.TreeModel`, [:obj:`Gtk.TreePath`]) {{ docs }}
[ ":", "returns", ":", "A", "list", "containing", "a", ":", "obj", ":", "Gtk", ".", "TreePath", "for", "each", "selected", "row", "and", "a", ":", "obj", ":", "Gtk", ".", "TreeModel", "or", ":", "obj", ":", "None", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/Gtk.py#L2197-L2209
train
pygobject/pgi
pgi/overrides/Gtk.py
TreeModelFilter.set_value
def set_value(self, iter, column, value): """Set the value of the child model""" # Delegate to child model iter = self.convert_iter_to_child_iter(iter) self.get_model().set_value(iter, column, value)
python
def set_value(self, iter, column, value): """Set the value of the child model""" # Delegate to child model iter = self.convert_iter_to_child_iter(iter) self.get_model().set_value(iter, column, value)
[ "def", "set_value", "(", "self", ",", "iter", ",", "column", ",", "value", ")", ":", "# Delegate to child model", "iter", "=", "self", ".", "convert_iter_to_child_iter", "(", "iter", ")", "self", ".", "get_model", "(", ")", ".", "set_value", "(", "iter", ",", "column", ",", "value", ")" ]
Set the value of the child model
[ "Set", "the", "value", "of", "the", "child", "model" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/Gtk.py#L2376-L2381
train
pygobject/pgi
pgi/foreign/__init__.py
get_foreign_module
def get_foreign_module(namespace): """Returns the module or raises ForeignError""" if namespace not in _MODULES: try: module = importlib.import_module("." + namespace, __package__) except ImportError: module = None _MODULES[namespace] = module module = _MODULES.get(namespace) if module is None: raise ForeignError("Foreign %r structs not supported" % namespace) return module
python
def get_foreign_module(namespace): """Returns the module or raises ForeignError""" if namespace not in _MODULES: try: module = importlib.import_module("." + namespace, __package__) except ImportError: module = None _MODULES[namespace] = module module = _MODULES.get(namespace) if module is None: raise ForeignError("Foreign %r structs not supported" % namespace) return module
[ "def", "get_foreign_module", "(", "namespace", ")", ":", "if", "namespace", "not", "in", "_MODULES", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "\".\"", "+", "namespace", ",", "__package__", ")", "except", "ImportError", ":", "module", "=", "None", "_MODULES", "[", "namespace", "]", "=", "module", "module", "=", "_MODULES", ".", "get", "(", "namespace", ")", "if", "module", "is", "None", ":", "raise", "ForeignError", "(", "\"Foreign %r structs not supported\"", "%", "namespace", ")", "return", "module" ]
Returns the module or raises ForeignError
[ "Returns", "the", "module", "or", "raises", "ForeignError" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/foreign/__init__.py#L21-L34
train
pygobject/pgi
pgi/foreign/__init__.py
get_foreign_struct
def get_foreign_struct(namespace, name): """Returns a ForeignStruct implementation or raises ForeignError""" get_foreign_module(namespace) try: return ForeignStruct.get(namespace, name) except KeyError: raise ForeignError("Foreign %s.%s not supported" % (namespace, name))
python
def get_foreign_struct(namespace, name): """Returns a ForeignStruct implementation or raises ForeignError""" get_foreign_module(namespace) try: return ForeignStruct.get(namespace, name) except KeyError: raise ForeignError("Foreign %s.%s not supported" % (namespace, name))
[ "def", "get_foreign_struct", "(", "namespace", ",", "name", ")", ":", "get_foreign_module", "(", "namespace", ")", "try", ":", "return", "ForeignStruct", ".", "get", "(", "namespace", ",", "name", ")", "except", "KeyError", ":", "raise", "ForeignError", "(", "\"Foreign %s.%s not supported\"", "%", "(", "namespace", ",", "name", ")", ")" ]
Returns a ForeignStruct implementation or raises ForeignError
[ "Returns", "a", "ForeignStruct", "implementation", "or", "raises", "ForeignError" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/foreign/__init__.py#L37-L45
train
pygobject/pgi
pgi/foreign/__init__.py
require_foreign
def require_foreign(namespace, symbol=None): """Raises ImportError if the specified foreign module isn't supported or the needed dependencies aren't installed. e.g.: check_foreign('cairo', 'Context') """ try: if symbol is None: get_foreign_module(namespace) else: get_foreign_struct(namespace, symbol) except ForeignError as e: raise ImportError(e)
python
def require_foreign(namespace, symbol=None): """Raises ImportError if the specified foreign module isn't supported or the needed dependencies aren't installed. e.g.: check_foreign('cairo', 'Context') """ try: if symbol is None: get_foreign_module(namespace) else: get_foreign_struct(namespace, symbol) except ForeignError as e: raise ImportError(e)
[ "def", "require_foreign", "(", "namespace", ",", "symbol", "=", "None", ")", ":", "try", ":", "if", "symbol", "is", "None", ":", "get_foreign_module", "(", "namespace", ")", "else", ":", "get_foreign_struct", "(", "namespace", ",", "symbol", ")", "except", "ForeignError", "as", "e", ":", "raise", "ImportError", "(", "e", ")" ]
Raises ImportError if the specified foreign module isn't supported or the needed dependencies aren't installed. e.g.: check_foreign('cairo', 'Context')
[ "Raises", "ImportError", "if", "the", "specified", "foreign", "module", "isn", "t", "supported", "or", "the", "needed", "dependencies", "aren", "t", "installed", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/foreign/__init__.py#L48-L62
train
pygobject/pgi
pgi/overrides/GLib.py
io_add_watch
def io_add_watch(*args, **kwargs): """io_add_watch(channel, priority, condition, func, *user_data) -> event_source_id""" channel, priority, condition, func, user_data = _io_add_watch_get_args(*args, **kwargs) return GLib.io_add_watch(channel, priority, condition, func, *user_data)
python
def io_add_watch(*args, **kwargs): """io_add_watch(channel, priority, condition, func, *user_data) -> event_source_id""" channel, priority, condition, func, user_data = _io_add_watch_get_args(*args, **kwargs) return GLib.io_add_watch(channel, priority, condition, func, *user_data)
[ "def", "io_add_watch", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "channel", ",", "priority", ",", "condition", ",", "func", ",", "user_data", "=", "_io_add_watch_get_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "GLib", ".", "io_add_watch", "(", "channel", ",", "priority", ",", "condition", ",", "func", ",", "*", "user_data", ")" ]
io_add_watch(channel, priority, condition, func, *user_data) -> event_source_id
[ "io_add_watch", "(", "channel", "priority", "condition", "func", "*", "user_data", ")", "-", ">", "event_source_id" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L813-L816
train
pygobject/pgi
pgi/overrides/GLib.py
child_watch_add
def child_watch_add(*args, **kwargs): """child_watch_add(priority, pid, function, *data)""" priority, pid, function, data = _child_watch_add_get_args(*args, **kwargs) return GLib.child_watch_add(priority, pid, function, *data)
python
def child_watch_add(*args, **kwargs): """child_watch_add(priority, pid, function, *data)""" priority, pid, function, data = _child_watch_add_get_args(*args, **kwargs) return GLib.child_watch_add(priority, pid, function, *data)
[ "def", "child_watch_add", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "priority", ",", "pid", ",", "function", ",", "data", "=", "_child_watch_add_get_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "GLib", ".", "child_watch_add", "(", "priority", ",", "pid", ",", "function", ",", "*", "data", ")" ]
child_watch_add(priority, pid, function, *data)
[ "child_watch_add", "(", "priority", "pid", "function", "*", "data", ")" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L964-L967
train
pygobject/pgi
pgi/overrides/GLib.py
_VariantCreator._create
def _create(self, format, args): """Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remainder of the format string, and the remainder of the arguments. If args is None, then this won't actually consume any arguments, and just parse the format string and generate empty GVariant structures. This is required for creating empty dictionaries or arrays. """ # leaves (simple types) constructor = self._LEAF_CONSTRUCTORS.get(format[0]) if constructor: if args is not None: if not args: raise TypeError('not enough arguments for GVariant format string') v = constructor(args[0]) return (v, format[1:], args[1:]) else: return (None, format[1:], None) if format[0] == '(': return self._create_tuple(format, args) if format.startswith('a{'): return self._create_dict(format, args) if format[0] == 'a': return self._create_array(format, args) raise NotImplementedError('cannot handle GVariant type ' + format)
python
def _create(self, format, args): """Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remainder of the format string, and the remainder of the arguments. If args is None, then this won't actually consume any arguments, and just parse the format string and generate empty GVariant structures. This is required for creating empty dictionaries or arrays. """ # leaves (simple types) constructor = self._LEAF_CONSTRUCTORS.get(format[0]) if constructor: if args is not None: if not args: raise TypeError('not enough arguments for GVariant format string') v = constructor(args[0]) return (v, format[1:], args[1:]) else: return (None, format[1:], None) if format[0] == '(': return self._create_tuple(format, args) if format.startswith('a{'): return self._create_dict(format, args) if format[0] == 'a': return self._create_array(format, args) raise NotImplementedError('cannot handle GVariant type ' + format)
[ "def", "_create", "(", "self", ",", "format", ",", "args", ")", ":", "# leaves (simple types)", "constructor", "=", "self", ".", "_LEAF_CONSTRUCTORS", ".", "get", "(", "format", "[", "0", "]", ")", "if", "constructor", ":", "if", "args", "is", "not", "None", ":", "if", "not", "args", ":", "raise", "TypeError", "(", "'not enough arguments for GVariant format string'", ")", "v", "=", "constructor", "(", "args", "[", "0", "]", ")", "return", "(", "v", ",", "format", "[", "1", ":", "]", ",", "args", "[", "1", ":", "]", ")", "else", ":", "return", "(", "None", ",", "format", "[", "1", ":", "]", ",", "None", ")", "if", "format", "[", "0", "]", "==", "'('", ":", "return", "self", ".", "_create_tuple", "(", "format", ",", "args", ")", "if", "format", ".", "startswith", "(", "'a{'", ")", ":", "return", "self", ".", "_create_dict", "(", "format", ",", "args", ")", "if", "format", "[", "0", "]", "==", "'a'", ":", "return", "self", ".", "_create_array", "(", "format", ",", "args", ")", "raise", "NotImplementedError", "(", "'cannot handle GVariant type '", "+", "format", ")" ]
Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remainder of the format string, and the remainder of the arguments. If args is None, then this won't actually consume any arguments, and just parse the format string and generate empty GVariant structures. This is required for creating empty dictionaries or arrays.
[ "Create", "a", "GVariant", "object", "from", "given", "format", "and", "argument", "list", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L153-L187
train
pygobject/pgi
pgi/overrides/GLib.py
_VariantCreator._create_tuple
def _create_tuple(self, format, args): """Handle the case where the outermost type of format is a tuple.""" format = format[1:] # eat the '(' if args is None: # empty value: we need to call _create() to parse the subtype rest_format = format while rest_format: if rest_format.startswith(')'): break rest_format = self._create(rest_format, None)[1] else: raise TypeError('tuple type string not closed with )') rest_format = rest_format[1:] # eat the ) return (None, rest_format, None) else: if not args or not isinstance(args[0], tuple): raise TypeError('expected tuple argument') builder = GLib.VariantBuilder.new(variant_type_from_string('r')) for i in range(len(args[0])): if format.startswith(')'): raise TypeError('too many arguments for tuple signature') (v, format, _) = self._create(format, args[0][i:]) builder.add_value(v) args = args[1:] if not format.startswith(')'): raise TypeError('tuple type string not closed with )') rest_format = format[1:] # eat the ) return (builder.end(), rest_format, args)
python
def _create_tuple(self, format, args): """Handle the case where the outermost type of format is a tuple.""" format = format[1:] # eat the '(' if args is None: # empty value: we need to call _create() to parse the subtype rest_format = format while rest_format: if rest_format.startswith(')'): break rest_format = self._create(rest_format, None)[1] else: raise TypeError('tuple type string not closed with )') rest_format = rest_format[1:] # eat the ) return (None, rest_format, None) else: if not args or not isinstance(args[0], tuple): raise TypeError('expected tuple argument') builder = GLib.VariantBuilder.new(variant_type_from_string('r')) for i in range(len(args[0])): if format.startswith(')'): raise TypeError('too many arguments for tuple signature') (v, format, _) = self._create(format, args[0][i:]) builder.add_value(v) args = args[1:] if not format.startswith(')'): raise TypeError('tuple type string not closed with )') rest_format = format[1:] # eat the ) return (builder.end(), rest_format, args)
[ "def", "_create_tuple", "(", "self", ",", "format", ",", "args", ")", ":", "format", "=", "format", "[", "1", ":", "]", "# eat the '('", "if", "args", "is", "None", ":", "# empty value: we need to call _create() to parse the subtype", "rest_format", "=", "format", "while", "rest_format", ":", "if", "rest_format", ".", "startswith", "(", "')'", ")", ":", "break", "rest_format", "=", "self", ".", "_create", "(", "rest_format", ",", "None", ")", "[", "1", "]", "else", ":", "raise", "TypeError", "(", "'tuple type string not closed with )'", ")", "rest_format", "=", "rest_format", "[", "1", ":", "]", "# eat the )", "return", "(", "None", ",", "rest_format", ",", "None", ")", "else", ":", "if", "not", "args", "or", "not", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "raise", "TypeError", "(", "'expected tuple argument'", ")", "builder", "=", "GLib", ".", "VariantBuilder", ".", "new", "(", "variant_type_from_string", "(", "'r'", ")", ")", "for", "i", "in", "range", "(", "len", "(", "args", "[", "0", "]", ")", ")", ":", "if", "format", ".", "startswith", "(", "')'", ")", ":", "raise", "TypeError", "(", "'too many arguments for tuple signature'", ")", "(", "v", ",", "format", ",", "_", ")", "=", "self", ".", "_create", "(", "format", ",", "args", "[", "0", "]", "[", "i", ":", "]", ")", "builder", ".", "add_value", "(", "v", ")", "args", "=", "args", "[", "1", ":", "]", "if", "not", "format", ".", "startswith", "(", "')'", ")", ":", "raise", "TypeError", "(", "'tuple type string not closed with )'", ")", "rest_format", "=", "format", "[", "1", ":", "]", "# eat the )", "return", "(", "builder", ".", "end", "(", ")", ",", "rest_format", ",", "args", ")" ]
Handle the case where the outermost type of format is a tuple.
[ "Handle", "the", "case", "where", "the", "outermost", "type", "of", "format", "is", "a", "tuple", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L189-L221
train
pygobject/pgi
pgi/overrides/GLib.py
_VariantCreator._create_dict
def _create_dict(self, format, args): """Handle the case where the outermost type of format is a dict.""" builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely rest_format = self._create(format[2:], None)[1] rest_format = self._create(rest_format, None)[1] if not rest_format.startswith('}'): raise TypeError('dictionary type string not closed with }') rest_format = rest_format[1:] # eat the } element_type = format[:len(format) - len(rest_format)] builder = GLib.VariantBuilder.new(variant_type_from_string(element_type)) else: builder = GLib.VariantBuilder.new(variant_type_from_string('a{?*}')) for k, v in args[0].items(): (key_v, rest_format, _) = self._create(format[2:], [k]) (val_v, rest_format, _) = self._create(rest_format, [v]) if not rest_format.startswith('}'): raise TypeError('dictionary type string not closed with }') rest_format = rest_format[1:] # eat the } entry = GLib.VariantBuilder.new(variant_type_from_string('{?*}')) entry.add_value(key_v) entry.add_value(val_v) builder.add_value(entry.end()) if args is not None: args = args[1:] return (builder.end(), rest_format, args)
python
def _create_dict(self, format, args): """Handle the case where the outermost type of format is a dict.""" builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely rest_format = self._create(format[2:], None)[1] rest_format = self._create(rest_format, None)[1] if not rest_format.startswith('}'): raise TypeError('dictionary type string not closed with }') rest_format = rest_format[1:] # eat the } element_type = format[:len(format) - len(rest_format)] builder = GLib.VariantBuilder.new(variant_type_from_string(element_type)) else: builder = GLib.VariantBuilder.new(variant_type_from_string('a{?*}')) for k, v in args[0].items(): (key_v, rest_format, _) = self._create(format[2:], [k]) (val_v, rest_format, _) = self._create(rest_format, [v]) if not rest_format.startswith('}'): raise TypeError('dictionary type string not closed with }') rest_format = rest_format[1:] # eat the } entry = GLib.VariantBuilder.new(variant_type_from_string('{?*}')) entry.add_value(key_v) entry.add_value(val_v) builder.add_value(entry.end()) if args is not None: args = args[1:] return (builder.end(), rest_format, args)
[ "def", "_create_dict", "(", "self", ",", "format", ",", "args", ")", ":", "builder", "=", "None", "if", "args", "is", "None", "or", "not", "args", "[", "0", "]", ":", "# empty value: we need to call _create() to parse the subtype,", "# and specify the element type precisely", "rest_format", "=", "self", ".", "_create", "(", "format", "[", "2", ":", "]", ",", "None", ")", "[", "1", "]", "rest_format", "=", "self", ".", "_create", "(", "rest_format", ",", "None", ")", "[", "1", "]", "if", "not", "rest_format", ".", "startswith", "(", "'}'", ")", ":", "raise", "TypeError", "(", "'dictionary type string not closed with }'", ")", "rest_format", "=", "rest_format", "[", "1", ":", "]", "# eat the }", "element_type", "=", "format", "[", ":", "len", "(", "format", ")", "-", "len", "(", "rest_format", ")", "]", "builder", "=", "GLib", ".", "VariantBuilder", ".", "new", "(", "variant_type_from_string", "(", "element_type", ")", ")", "else", ":", "builder", "=", "GLib", ".", "VariantBuilder", ".", "new", "(", "variant_type_from_string", "(", "'a{?*}'", ")", ")", "for", "k", ",", "v", "in", "args", "[", "0", "]", ".", "items", "(", ")", ":", "(", "key_v", ",", "rest_format", ",", "_", ")", "=", "self", ".", "_create", "(", "format", "[", "2", ":", "]", ",", "[", "k", "]", ")", "(", "val_v", ",", "rest_format", ",", "_", ")", "=", "self", ".", "_create", "(", "rest_format", ",", "[", "v", "]", ")", "if", "not", "rest_format", ".", "startswith", "(", "'}'", ")", ":", "raise", "TypeError", "(", "'dictionary type string not closed with }'", ")", "rest_format", "=", "rest_format", "[", "1", ":", "]", "# eat the }", "entry", "=", "GLib", ".", "VariantBuilder", ".", "new", "(", "variant_type_from_string", "(", "'{?*}'", ")", ")", "entry", ".", "add_value", "(", "key_v", ")", "entry", ".", "add_value", "(", "val_v", ")", "builder", ".", "add_value", "(", "entry", ".", "end", "(", ")", ")", "if", "args", "is", "not", "None", ":", "args", "=", "args", "[", "1", ":", "]", "return", "(", "builder", ".", "end", "(", ")", ",", "rest_format", ",", "args", ")" ]
Handle the case where the outermost type of format is a dict.
[ "Handle", "the", "case", "where", "the", "outermost", "type", "of", "format", "is", "a", "dict", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L223-L254
train
pygobject/pgi
pgi/overrides/GLib.py
_VariantCreator._create_array
def _create_array(self, format, args): """Handle the case where the outermost type of format is an array.""" builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely rest_format = self._create(format[1:], None)[1] element_type = format[:len(format) - len(rest_format)] builder = GLib.VariantBuilder.new(variant_type_from_string(element_type)) else: builder = GLib.VariantBuilder.new(variant_type_from_string('a*')) for i in range(len(args[0])): (v, rest_format, _) = self._create(format[1:], args[0][i:]) builder.add_value(v) if args is not None: args = args[1:] return (builder.end(), rest_format, args)
python
def _create_array(self, format, args): """Handle the case where the outermost type of format is an array.""" builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely rest_format = self._create(format[1:], None)[1] element_type = format[:len(format) - len(rest_format)] builder = GLib.VariantBuilder.new(variant_type_from_string(element_type)) else: builder = GLib.VariantBuilder.new(variant_type_from_string('a*')) for i in range(len(args[0])): (v, rest_format, _) = self._create(format[1:], args[0][i:]) builder.add_value(v) if args is not None: args = args[1:] return (builder.end(), rest_format, args)
[ "def", "_create_array", "(", "self", ",", "format", ",", "args", ")", ":", "builder", "=", "None", "if", "args", "is", "None", "or", "not", "args", "[", "0", "]", ":", "# empty value: we need to call _create() to parse the subtype,", "# and specify the element type precisely", "rest_format", "=", "self", ".", "_create", "(", "format", "[", "1", ":", "]", ",", "None", ")", "[", "1", "]", "element_type", "=", "format", "[", ":", "len", "(", "format", ")", "-", "len", "(", "rest_format", ")", "]", "builder", "=", "GLib", ".", "VariantBuilder", ".", "new", "(", "variant_type_from_string", "(", "element_type", ")", ")", "else", ":", "builder", "=", "GLib", ".", "VariantBuilder", ".", "new", "(", "variant_type_from_string", "(", "'a*'", ")", ")", "for", "i", "in", "range", "(", "len", "(", "args", "[", "0", "]", ")", ")", ":", "(", "v", ",", "rest_format", ",", "_", ")", "=", "self", ".", "_create", "(", "format", "[", "1", ":", "]", ",", "args", "[", "0", "]", "[", "i", ":", "]", ")", "builder", ".", "add_value", "(", "v", ")", "if", "args", "is", "not", "None", ":", "args", "=", "args", "[", "1", ":", "]", "return", "(", "builder", ".", "end", "(", ")", ",", "rest_format", ",", "args", ")" ]
Handle the case where the outermost type of format is an array.
[ "Handle", "the", "case", "where", "the", "outermost", "type", "of", "format", "is", "an", "array", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L256-L273
train
pygobject/pgi
pgi/overrides/GLib.py
Variant.unpack
def unpack(self): """Decompose a GVariant into a native Python object.""" LEAF_ACCESSORS = { 'b': self.get_boolean, 'y': self.get_byte, 'n': self.get_int16, 'q': self.get_uint16, 'i': self.get_int32, 'u': self.get_uint32, 'x': self.get_int64, 't': self.get_uint64, 'h': self.get_handle, 'd': self.get_double, 's': self.get_string, 'o': self.get_string, # object path 'g': self.get_string, # signature } # simple values la = LEAF_ACCESSORS.get(self.get_type_string()) if la: return la() # tuple if self.get_type_string().startswith('('): res = [self.get_child_value(i).unpack() for i in range(self.n_children())] return tuple(res) # dictionary if self.get_type_string().startswith('a{'): res = {} for i in range(self.n_children()): v = self.get_child_value(i) res[v.get_child_value(0).unpack()] = v.get_child_value(1).unpack() return res # array if self.get_type_string().startswith('a'): return [self.get_child_value(i).unpack() for i in range(self.n_children())] # variant (just unbox transparently) if self.get_type_string().startswith('v'): return self.get_variant().unpack() # maybe if self.get_type_string().startswith('m'): m = self.get_maybe() return m.unpack() if m else None raise NotImplementedError('unsupported GVariant type ' + self.get_type_string())
python
def unpack(self): """Decompose a GVariant into a native Python object.""" LEAF_ACCESSORS = { 'b': self.get_boolean, 'y': self.get_byte, 'n': self.get_int16, 'q': self.get_uint16, 'i': self.get_int32, 'u': self.get_uint32, 'x': self.get_int64, 't': self.get_uint64, 'h': self.get_handle, 'd': self.get_double, 's': self.get_string, 'o': self.get_string, # object path 'g': self.get_string, # signature } # simple values la = LEAF_ACCESSORS.get(self.get_type_string()) if la: return la() # tuple if self.get_type_string().startswith('('): res = [self.get_child_value(i).unpack() for i in range(self.n_children())] return tuple(res) # dictionary if self.get_type_string().startswith('a{'): res = {} for i in range(self.n_children()): v = self.get_child_value(i) res[v.get_child_value(0).unpack()] = v.get_child_value(1).unpack() return res # array if self.get_type_string().startswith('a'): return [self.get_child_value(i).unpack() for i in range(self.n_children())] # variant (just unbox transparently) if self.get_type_string().startswith('v'): return self.get_variant().unpack() # maybe if self.get_type_string().startswith('m'): m = self.get_maybe() return m.unpack() if m else None raise NotImplementedError('unsupported GVariant type ' + self.get_type_string())
[ "def", "unpack", "(", "self", ")", ":", "LEAF_ACCESSORS", "=", "{", "'b'", ":", "self", ".", "get_boolean", ",", "'y'", ":", "self", ".", "get_byte", ",", "'n'", ":", "self", ".", "get_int16", ",", "'q'", ":", "self", ".", "get_uint16", ",", "'i'", ":", "self", ".", "get_int32", ",", "'u'", ":", "self", ".", "get_uint32", ",", "'x'", ":", "self", ".", "get_int64", ",", "'t'", ":", "self", ".", "get_uint64", ",", "'h'", ":", "self", ".", "get_handle", ",", "'d'", ":", "self", ".", "get_double", ",", "'s'", ":", "self", ".", "get_string", ",", "'o'", ":", "self", ".", "get_string", ",", "# object path", "'g'", ":", "self", ".", "get_string", ",", "# signature", "}", "# simple values", "la", "=", "LEAF_ACCESSORS", ".", "get", "(", "self", ".", "get_type_string", "(", ")", ")", "if", "la", ":", "return", "la", "(", ")", "# tuple", "if", "self", ".", "get_type_string", "(", ")", ".", "startswith", "(", "'('", ")", ":", "res", "=", "[", "self", ".", "get_child_value", "(", "i", ")", ".", "unpack", "(", ")", "for", "i", "in", "range", "(", "self", ".", "n_children", "(", ")", ")", "]", "return", "tuple", "(", "res", ")", "# dictionary", "if", "self", ".", "get_type_string", "(", ")", ".", "startswith", "(", "'a{'", ")", ":", "res", "=", "{", "}", "for", "i", "in", "range", "(", "self", ".", "n_children", "(", ")", ")", ":", "v", "=", "self", ".", "get_child_value", "(", "i", ")", "res", "[", "v", ".", "get_child_value", "(", "0", ")", ".", "unpack", "(", ")", "]", "=", "v", ".", "get_child_value", "(", "1", ")", ".", "unpack", "(", ")", "return", "res", "# array", "if", "self", ".", "get_type_string", "(", ")", ".", "startswith", "(", "'a'", ")", ":", "return", "[", "self", ".", "get_child_value", "(", "i", ")", ".", "unpack", "(", ")", "for", "i", "in", "range", "(", "self", ".", "n_children", "(", ")", ")", "]", "# variant (just unbox transparently)", "if", "self", ".", "get_type_string", "(", ")", ".", "startswith", "(", "'v'", ")", ":", "return", "self", ".", "get_variant", "(", ")", ".", "unpack", "(", ")", "# maybe", "if", "self", ".", "get_type_string", "(", ")", ".", "startswith", "(", "'m'", ")", ":", "m", "=", "self", ".", "get_maybe", "(", ")", "return", "m", ".", "unpack", "(", ")", "if", "m", "else", "None", "raise", "NotImplementedError", "(", "'unsupported GVariant type '", "+", "self", ".", "get_type_string", "(", ")", ")" ]
Decompose a GVariant into a native Python object.
[ "Decompose", "a", "GVariant", "into", "a", "native", "Python", "object", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L342-L394
train
pygobject/pgi
pgi/overrides/GLib.py
Variant.split_signature
def split_signature(klass, signature): """Return a list of the element signatures of the topmost signature tuple. If the signature is not a tuple, it returns one element with the entire signature. If the signature is an empty tuple, the result is []. This is useful for e. g. iterating over method parameters which are passed as a single Variant. """ if signature == '()': return [] if not signature.startswith('('): return [signature] result = [] head = '' tail = signature[1:-1] # eat the surrounding () while tail: c = tail[0] head += c tail = tail[1:] if c in ('m', 'a'): # prefixes, keep collecting continue if c in ('(', '{'): # consume until corresponding )/} level = 1 up = c if up == '(': down = ')' else: down = '}' while level > 0: c = tail[0] head += c tail = tail[1:] if c == up: level += 1 elif c == down: level -= 1 # otherwise we have a simple type result.append(head) head = '' return result
python
def split_signature(klass, signature): """Return a list of the element signatures of the topmost signature tuple. If the signature is not a tuple, it returns one element with the entire signature. If the signature is an empty tuple, the result is []. This is useful for e. g. iterating over method parameters which are passed as a single Variant. """ if signature == '()': return [] if not signature.startswith('('): return [signature] result = [] head = '' tail = signature[1:-1] # eat the surrounding () while tail: c = tail[0] head += c tail = tail[1:] if c in ('m', 'a'): # prefixes, keep collecting continue if c in ('(', '{'): # consume until corresponding )/} level = 1 up = c if up == '(': down = ')' else: down = '}' while level > 0: c = tail[0] head += c tail = tail[1:] if c == up: level += 1 elif c == down: level -= 1 # otherwise we have a simple type result.append(head) head = '' return result
[ "def", "split_signature", "(", "klass", ",", "signature", ")", ":", "if", "signature", "==", "'()'", ":", "return", "[", "]", "if", "not", "signature", ".", "startswith", "(", "'('", ")", ":", "return", "[", "signature", "]", "result", "=", "[", "]", "head", "=", "''", "tail", "=", "signature", "[", "1", ":", "-", "1", "]", "# eat the surrounding ()", "while", "tail", ":", "c", "=", "tail", "[", "0", "]", "head", "+=", "c", "tail", "=", "tail", "[", "1", ":", "]", "if", "c", "in", "(", "'m'", ",", "'a'", ")", ":", "# prefixes, keep collecting", "continue", "if", "c", "in", "(", "'('", ",", "'{'", ")", ":", "# consume until corresponding )/}", "level", "=", "1", "up", "=", "c", "if", "up", "==", "'('", ":", "down", "=", "')'", "else", ":", "down", "=", "'}'", "while", "level", ">", "0", ":", "c", "=", "tail", "[", "0", "]", "head", "+=", "c", "tail", "=", "tail", "[", "1", ":", "]", "if", "c", "==", "up", ":", "level", "+=", "1", "elif", "c", "==", "down", ":", "level", "-=", "1", "# otherwise we have a simple type", "result", ".", "append", "(", "head", ")", "head", "=", "''", "return", "result" ]
Return a list of the element signatures of the topmost signature tuple. If the signature is not a tuple, it returns one element with the entire signature. If the signature is an empty tuple, the result is []. This is useful for e. g. iterating over method parameters which are passed as a single Variant.
[ "Return", "a", "list", "of", "the", "element", "signatures", "of", "the", "topmost", "signature", "tuple", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GLib.py#L397-L444
train
pygobject/pgi
pgi/codegen/ctypes_backend/utils.py
typeinfo_to_ctypes
def typeinfo_to_ctypes(info, return_value=False): """Maps a GITypeInfo() to a ctypes type. The ctypes types have to be different in the case of return values since ctypes does 'auto unboxing' in some cases which gives us no chance to free memory if there is a ownership transfer. """ tag = info.tag.value ptr = info.is_pointer mapping = { GITypeTag.BOOLEAN: gboolean, GITypeTag.INT8: gint8, GITypeTag.UINT8: guint8, GITypeTag.INT16: gint16, GITypeTag.UINT16: guint16, GITypeTag.INT32: gint32, GITypeTag.UINT32: guint32, GITypeTag.INT64: gint64, GITypeTag.UINT64: guint64, GITypeTag.FLOAT: gfloat, GITypeTag.DOUBLE: gdouble, GITypeTag.VOID: None, GITypeTag.GTYPE: GType, GITypeTag.UNICHAR: gunichar, } if ptr: if tag == GITypeTag.INTERFACE: return gpointer elif tag in (GITypeTag.UTF8, GITypeTag.FILENAME): if return_value: # ctypes does auto conversion to str and gives us no chance # to free the pointer if transfer=everything return gpointer else: return gchar_p elif tag == GITypeTag.ARRAY: return gpointer elif tag == GITypeTag.ERROR: return GErrorPtr elif tag == GITypeTag.GLIST: return GListPtr elif tag == GITypeTag.GSLIST: return GSListPtr else: if tag in mapping: return ctypes.POINTER(mapping[tag]) else: if tag == GITypeTag.INTERFACE: iface = info.get_interface() iface_type = iface.type.value if iface_type == GIInfoType.ENUM: return guint32 elif iface_type == GIInfoType.OBJECT: return gpointer elif iface_type == GIInfoType.STRUCT: return gpointer elif iface_type == GIInfoType.UNION: return gpointer elif iface_type == GIInfoType.FLAGS: return guint elif iface_type == GIInfoType.CALLBACK: return GCallback raise NotImplementedError( "Could not convert interface: %r to ctypes type" % iface.type) else: if tag in mapping: return mapping[tag] raise NotImplementedError("Could not convert %r to ctypes type" % info.tag)
python
def typeinfo_to_ctypes(info, return_value=False): """Maps a GITypeInfo() to a ctypes type. The ctypes types have to be different in the case of return values since ctypes does 'auto unboxing' in some cases which gives us no chance to free memory if there is a ownership transfer. """ tag = info.tag.value ptr = info.is_pointer mapping = { GITypeTag.BOOLEAN: gboolean, GITypeTag.INT8: gint8, GITypeTag.UINT8: guint8, GITypeTag.INT16: gint16, GITypeTag.UINT16: guint16, GITypeTag.INT32: gint32, GITypeTag.UINT32: guint32, GITypeTag.INT64: gint64, GITypeTag.UINT64: guint64, GITypeTag.FLOAT: gfloat, GITypeTag.DOUBLE: gdouble, GITypeTag.VOID: None, GITypeTag.GTYPE: GType, GITypeTag.UNICHAR: gunichar, } if ptr: if tag == GITypeTag.INTERFACE: return gpointer elif tag in (GITypeTag.UTF8, GITypeTag.FILENAME): if return_value: # ctypes does auto conversion to str and gives us no chance # to free the pointer if transfer=everything return gpointer else: return gchar_p elif tag == GITypeTag.ARRAY: return gpointer elif tag == GITypeTag.ERROR: return GErrorPtr elif tag == GITypeTag.GLIST: return GListPtr elif tag == GITypeTag.GSLIST: return GSListPtr else: if tag in mapping: return ctypes.POINTER(mapping[tag]) else: if tag == GITypeTag.INTERFACE: iface = info.get_interface() iface_type = iface.type.value if iface_type == GIInfoType.ENUM: return guint32 elif iface_type == GIInfoType.OBJECT: return gpointer elif iface_type == GIInfoType.STRUCT: return gpointer elif iface_type == GIInfoType.UNION: return gpointer elif iface_type == GIInfoType.FLAGS: return guint elif iface_type == GIInfoType.CALLBACK: return GCallback raise NotImplementedError( "Could not convert interface: %r to ctypes type" % iface.type) else: if tag in mapping: return mapping[tag] raise NotImplementedError("Could not convert %r to ctypes type" % info.tag)
[ "def", "typeinfo_to_ctypes", "(", "info", ",", "return_value", "=", "False", ")", ":", "tag", "=", "info", ".", "tag", ".", "value", "ptr", "=", "info", ".", "is_pointer", "mapping", "=", "{", "GITypeTag", ".", "BOOLEAN", ":", "gboolean", ",", "GITypeTag", ".", "INT8", ":", "gint8", ",", "GITypeTag", ".", "UINT8", ":", "guint8", ",", "GITypeTag", ".", "INT16", ":", "gint16", ",", "GITypeTag", ".", "UINT16", ":", "guint16", ",", "GITypeTag", ".", "INT32", ":", "gint32", ",", "GITypeTag", ".", "UINT32", ":", "guint32", ",", "GITypeTag", ".", "INT64", ":", "gint64", ",", "GITypeTag", ".", "UINT64", ":", "guint64", ",", "GITypeTag", ".", "FLOAT", ":", "gfloat", ",", "GITypeTag", ".", "DOUBLE", ":", "gdouble", ",", "GITypeTag", ".", "VOID", ":", "None", ",", "GITypeTag", ".", "GTYPE", ":", "GType", ",", "GITypeTag", ".", "UNICHAR", ":", "gunichar", ",", "}", "if", "ptr", ":", "if", "tag", "==", "GITypeTag", ".", "INTERFACE", ":", "return", "gpointer", "elif", "tag", "in", "(", "GITypeTag", ".", "UTF8", ",", "GITypeTag", ".", "FILENAME", ")", ":", "if", "return_value", ":", "# ctypes does auto conversion to str and gives us no chance", "# to free the pointer if transfer=everything", "return", "gpointer", "else", ":", "return", "gchar_p", "elif", "tag", "==", "GITypeTag", ".", "ARRAY", ":", "return", "gpointer", "elif", "tag", "==", "GITypeTag", ".", "ERROR", ":", "return", "GErrorPtr", "elif", "tag", "==", "GITypeTag", ".", "GLIST", ":", "return", "GListPtr", "elif", "tag", "==", "GITypeTag", ".", "GSLIST", ":", "return", "GSListPtr", "else", ":", "if", "tag", "in", "mapping", ":", "return", "ctypes", ".", "POINTER", "(", "mapping", "[", "tag", "]", ")", "else", ":", "if", "tag", "==", "GITypeTag", ".", "INTERFACE", ":", "iface", "=", "info", ".", "get_interface", "(", ")", "iface_type", "=", "iface", ".", "type", ".", "value", "if", "iface_type", "==", "GIInfoType", ".", "ENUM", ":", "return", "guint32", "elif", "iface_type", "==", "GIInfoType", ".", "OBJECT", ":", "return", "gpointer", "elif", "iface_type", "==", "GIInfoType", ".", "STRUCT", ":", "return", "gpointer", "elif", "iface_type", "==", "GIInfoType", ".", "UNION", ":", "return", "gpointer", "elif", "iface_type", "==", "GIInfoType", ".", "FLAGS", ":", "return", "guint", "elif", "iface_type", "==", "GIInfoType", ".", "CALLBACK", ":", "return", "GCallback", "raise", "NotImplementedError", "(", "\"Could not convert interface: %r to ctypes type\"", "%", "iface", ".", "type", ")", "else", ":", "if", "tag", "in", "mapping", ":", "return", "mapping", "[", "tag", "]", "raise", "NotImplementedError", "(", "\"Could not convert %r to ctypes type\"", "%", "info", ".", "tag", ")" ]
Maps a GITypeInfo() to a ctypes type. The ctypes types have to be different in the case of return values since ctypes does 'auto unboxing' in some cases which gives us no chance to free memory if there is a ownership transfer.
[ "Maps", "a", "GITypeInfo", "()", "to", "a", "ctypes", "type", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/ctypes_backend/utils.py#L96-L168
train
pygobject/pgi
pgi/codegen/ctypes_backend/utils.py
BaseType.pack_pointer
def pack_pointer(self, name): """Returns a pointer containing the value. This only works for int32/uint32/utf-8.. """ return self.parse(""" raise $_.TypeError('Can\\'t convert %(type_name)s to pointer: %%r' %% $in_) """ % {"type_name": type(self).__name__}, in_=name)["in_"]
python
def pack_pointer(self, name): """Returns a pointer containing the value. This only works for int32/uint32/utf-8.. """ return self.parse(""" raise $_.TypeError('Can\\'t convert %(type_name)s to pointer: %%r' %% $in_) """ % {"type_name": type(self).__name__}, in_=name)["in_"]
[ "def", "pack_pointer", "(", "self", ",", "name", ")", ":", "return", "self", ".", "parse", "(", "\"\"\"\nraise $_.TypeError('Can\\\\'t convert %(type_name)s to pointer: %%r' %% $in_)\n\"\"\"", "%", "{", "\"type_name\"", ":", "type", "(", "self", ")", ".", "__name__", "}", ",", "in_", "=", "name", ")", "[", "\"in_\"", "]" ]
Returns a pointer containing the value. This only works for int32/uint32/utf-8..
[ "Returns", "a", "pointer", "containing", "the", "value", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/ctypes_backend/utils.py#L78-L86
train
pygobject/pgi
pgi/clib/gir/gitypelib.py
GITypelib.new_from_memory
def new_from_memory(cls, data): """Takes bytes and returns a GITypelib, or raises GIError""" size = len(data) copy = g_memdup(data, size) ptr = cast(copy, POINTER(guint8)) try: with gerror(GIError) as error: return GITypelib._new_from_memory(ptr, size, error) except GIError: free(copy) raise
python
def new_from_memory(cls, data): """Takes bytes and returns a GITypelib, or raises GIError""" size = len(data) copy = g_memdup(data, size) ptr = cast(copy, POINTER(guint8)) try: with gerror(GIError) as error: return GITypelib._new_from_memory(ptr, size, error) except GIError: free(copy) raise
[ "def", "new_from_memory", "(", "cls", ",", "data", ")", ":", "size", "=", "len", "(", "data", ")", "copy", "=", "g_memdup", "(", "data", ",", "size", ")", "ptr", "=", "cast", "(", "copy", ",", "POINTER", "(", "guint8", ")", ")", "try", ":", "with", "gerror", "(", "GIError", ")", "as", "error", ":", "return", "GITypelib", ".", "_new_from_memory", "(", "ptr", ",", "size", ",", "error", ")", "except", "GIError", ":", "free", "(", "copy", ")", "raise" ]
Takes bytes and returns a GITypelib, or raises GIError
[ "Takes", "bytes", "and", "returns", "a", "GITypelib", "or", "raises", "GIError" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/gir/gitypelib.py#L28-L39
train
pygobject/pgi
pgi/cffilib/gir/gibaseinfo.py
GIBaseInfo._get_type
def _get_type(cls, ptr): """Get the subtype class for a pointer""" # fall back to the base class if unknown return cls.__types.get(lib.g_base_info_get_type(ptr), cls)
python
def _get_type(cls, ptr): """Get the subtype class for a pointer""" # fall back to the base class if unknown return cls.__types.get(lib.g_base_info_get_type(ptr), cls)
[ "def", "_get_type", "(", "cls", ",", "ptr", ")", ":", "# fall back to the base class if unknown", "return", "cls", ".", "__types", ".", "get", "(", "lib", ".", "g_base_info_get_type", "(", "ptr", ")", ",", "cls", ")" ]
Get the subtype class for a pointer
[ "Get", "the", "subtype", "class", "for", "a", "pointer" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/cffilib/gir/gibaseinfo.py#L42-L46
train
pygobject/pgi
pgi/obj.py
add_method
def add_method(info, target_cls, virtual=False, dont_replace=False): """Add a method to the target class""" # escape before prefixing, like pygobject name = escape_identifier(info.name) if virtual: name = "do_" + name attr = VirtualMethodAttribute(info, target_cls, name) else: attr = MethodAttribute(info, target_cls, name) if dont_replace and hasattr(target_cls, name): return setattr(target_cls, name, attr)
python
def add_method(info, target_cls, virtual=False, dont_replace=False): """Add a method to the target class""" # escape before prefixing, like pygobject name = escape_identifier(info.name) if virtual: name = "do_" + name attr = VirtualMethodAttribute(info, target_cls, name) else: attr = MethodAttribute(info, target_cls, name) if dont_replace and hasattr(target_cls, name): return setattr(target_cls, name, attr)
[ "def", "add_method", "(", "info", ",", "target_cls", ",", "virtual", "=", "False", ",", "dont_replace", "=", "False", ")", ":", "# escape before prefixing, like pygobject", "name", "=", "escape_identifier", "(", "info", ".", "name", ")", "if", "virtual", ":", "name", "=", "\"do_\"", "+", "name", "attr", "=", "VirtualMethodAttribute", "(", "info", ",", "target_cls", ",", "name", ")", "else", ":", "attr", "=", "MethodAttribute", "(", "info", ",", "target_cls", ",", "name", ")", "if", "dont_replace", "and", "hasattr", "(", "target_cls", ",", "name", ")", ":", "return", "setattr", "(", "target_cls", ",", "name", ",", "attr", ")" ]
Add a method to the target class
[ "Add", "a", "method", "to", "the", "target", "class" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L308-L322
train
pygobject/pgi
pgi/obj.py
InterfaceAttribute
def InterfaceAttribute(iface_info): """Creates a GInterface class""" # Create a new class cls = type(iface_info.name, (InterfaceBase,), dict(_Interface.__dict__)) cls.__module__ = iface_info.namespace # GType cls.__gtype__ = PGType(iface_info.g_type) # Properties cls.props = PropertyAttribute(iface_info) # Signals cls.signals = SignalsAttribute(iface_info) # Add constants for constant in iface_info.get_constants(): constant_name = constant.name attr = ConstantAttribute(constant) setattr(cls, constant_name, attr) # Add methods for method_info in iface_info.get_methods(): add_method(method_info, cls) # VFuncs for vfunc_info in iface_info.get_vfuncs(): add_method(vfunc_info, cls, virtual=True) cls._sigs = {} is_info = iface_info.get_iface_struct() if is_info: iface_struct = import_attribute(is_info.namespace, is_info.name) else: iface_struct = None def get_iface_struct(cls): if not iface_struct: return None ptr = cls.__gtype__._type.default_interface_ref() if not ptr: return None return iface_struct._from_pointer(addressof(ptr.contents)) setattr(cls, "_get_iface_struct", classmethod(get_iface_struct)) return cls
python
def InterfaceAttribute(iface_info): """Creates a GInterface class""" # Create a new class cls = type(iface_info.name, (InterfaceBase,), dict(_Interface.__dict__)) cls.__module__ = iface_info.namespace # GType cls.__gtype__ = PGType(iface_info.g_type) # Properties cls.props = PropertyAttribute(iface_info) # Signals cls.signals = SignalsAttribute(iface_info) # Add constants for constant in iface_info.get_constants(): constant_name = constant.name attr = ConstantAttribute(constant) setattr(cls, constant_name, attr) # Add methods for method_info in iface_info.get_methods(): add_method(method_info, cls) # VFuncs for vfunc_info in iface_info.get_vfuncs(): add_method(vfunc_info, cls, virtual=True) cls._sigs = {} is_info = iface_info.get_iface_struct() if is_info: iface_struct = import_attribute(is_info.namespace, is_info.name) else: iface_struct = None def get_iface_struct(cls): if not iface_struct: return None ptr = cls.__gtype__._type.default_interface_ref() if not ptr: return None return iface_struct._from_pointer(addressof(ptr.contents)) setattr(cls, "_get_iface_struct", classmethod(get_iface_struct)) return cls
[ "def", "InterfaceAttribute", "(", "iface_info", ")", ":", "# Create a new class", "cls", "=", "type", "(", "iface_info", ".", "name", ",", "(", "InterfaceBase", ",", ")", ",", "dict", "(", "_Interface", ".", "__dict__", ")", ")", "cls", ".", "__module__", "=", "iface_info", ".", "namespace", "# GType", "cls", ".", "__gtype__", "=", "PGType", "(", "iface_info", ".", "g_type", ")", "# Properties", "cls", ".", "props", "=", "PropertyAttribute", "(", "iface_info", ")", "# Signals", "cls", ".", "signals", "=", "SignalsAttribute", "(", "iface_info", ")", "# Add constants", "for", "constant", "in", "iface_info", ".", "get_constants", "(", ")", ":", "constant_name", "=", "constant", ".", "name", "attr", "=", "ConstantAttribute", "(", "constant", ")", "setattr", "(", "cls", ",", "constant_name", ",", "attr", ")", "# Add methods", "for", "method_info", "in", "iface_info", ".", "get_methods", "(", ")", ":", "add_method", "(", "method_info", ",", "cls", ")", "# VFuncs", "for", "vfunc_info", "in", "iface_info", ".", "get_vfuncs", "(", ")", ":", "add_method", "(", "vfunc_info", ",", "cls", ",", "virtual", "=", "True", ")", "cls", ".", "_sigs", "=", "{", "}", "is_info", "=", "iface_info", ".", "get_iface_struct", "(", ")", "if", "is_info", ":", "iface_struct", "=", "import_attribute", "(", "is_info", ".", "namespace", ",", "is_info", ".", "name", ")", "else", ":", "iface_struct", "=", "None", "def", "get_iface_struct", "(", "cls", ")", ":", "if", "not", "iface_struct", ":", "return", "None", "ptr", "=", "cls", ".", "__gtype__", ".", "_type", ".", "default_interface_ref", "(", ")", "if", "not", "ptr", ":", "return", "None", "return", "iface_struct", ".", "_from_pointer", "(", "addressof", "(", "ptr", ".", "contents", ")", ")", "setattr", "(", "cls", ",", "\"_get_iface_struct\"", ",", "classmethod", "(", "get_iface_struct", ")", ")", "return", "cls" ]
Creates a GInterface class
[ "Creates", "a", "GInterface", "class" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L341-L390
train
pygobject/pgi
pgi/obj.py
new_class_from_gtype
def new_class_from_gtype(gtype): """Create a new class for a gtype not in the gir. The caller is responsible for caching etc. """ if gtype.is_a(PGType.from_name("GObject")): parent = gtype.parent.pytype if parent is None or parent == PGType.from_name("void"): return interfaces = [i.pytype for i in gtype.interfaces] bases = tuple([parent] + interfaces) cls = type(gtype.name, bases, dict()) cls.__gtype__ = gtype return cls elif gtype.is_a(PGType.from_name("GEnum")): from pgi.enum import GEnumBase return GEnumBase
python
def new_class_from_gtype(gtype): """Create a new class for a gtype not in the gir. The caller is responsible for caching etc. """ if gtype.is_a(PGType.from_name("GObject")): parent = gtype.parent.pytype if parent is None or parent == PGType.from_name("void"): return interfaces = [i.pytype for i in gtype.interfaces] bases = tuple([parent] + interfaces) cls = type(gtype.name, bases, dict()) cls.__gtype__ = gtype return cls elif gtype.is_a(PGType.from_name("GEnum")): from pgi.enum import GEnumBase return GEnumBase
[ "def", "new_class_from_gtype", "(", "gtype", ")", ":", "if", "gtype", ".", "is_a", "(", "PGType", ".", "from_name", "(", "\"GObject\"", ")", ")", ":", "parent", "=", "gtype", ".", "parent", ".", "pytype", "if", "parent", "is", "None", "or", "parent", "==", "PGType", ".", "from_name", "(", "\"void\"", ")", ":", "return", "interfaces", "=", "[", "i", ".", "pytype", "for", "i", "in", "gtype", ".", "interfaces", "]", "bases", "=", "tuple", "(", "[", "parent", "]", "+", "interfaces", ")", "cls", "=", "type", "(", "gtype", ".", "name", ",", "bases", ",", "dict", "(", ")", ")", "cls", ".", "__gtype__", "=", "gtype", "return", "cls", "elif", "gtype", ".", "is_a", "(", "PGType", ".", "from_name", "(", "\"GEnum\"", ")", ")", ":", "from", "pgi", ".", "enum", "import", "GEnumBase", "return", "GEnumBase" ]
Create a new class for a gtype not in the gir. The caller is responsible for caching etc.
[ "Create", "a", "new", "class", "for", "a", "gtype", "not", "in", "the", "gir", ".", "The", "caller", "is", "responsible", "for", "caching", "etc", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L393-L411
train
pygobject/pgi
pgi/obj.py
ObjectAttribute
def ObjectAttribute(obj_info): """Creates a GObject class. It inherits from the base class and all interfaces it implements. """ if obj_info.name == "Object" and obj_info.namespace == "GObject": cls = Object else: # Get the parent class parent_obj = obj_info.get_parent() if parent_obj: attr = import_attribute(parent_obj.namespace, parent_obj.name) bases = (attr,) else: bases = (object,) # Get all object interfaces ifaces = [] for interface in obj_info.get_interfaces(): attr = import_attribute(interface.namespace, interface.name) # only add interfaces if the base classes don't have it for base in bases: if attr in base.__mro__: break else: ifaces.append(attr) # Combine them to a base class list if ifaces: bases = tuple(list(bases) + ifaces) # Create a new class cls = type(obj_info.name, bases, dict()) cls.__module__ = obj_info.namespace # Set root to unowned= False and InitiallyUnowned=True if obj_info.namespace == "GObject": if obj_info.name == "InitiallyUnowned": cls._unowned = True elif obj_info.name == "Object": cls._unowned = False # GType cls.__gtype__ = PGType(obj_info.g_type) if not obj_info.fundamental: # Constructor cache cls._constructors = {} # Properties setattr(cls, PROPS_NAME, PropertyAttribute(obj_info)) # Signals cls.signals = SignalsAttribute(obj_info) # Signals cls.__sigs__ = {} for sig_info in obj_info.get_signals(): signal_name = sig_info.name cls.__sigs__[signal_name] = sig_info # Add constants for constant in obj_info.get_constants(): constant_name = constant.name attr = ConstantAttribute(constant) setattr(cls, constant_name, attr) # Fields for field in obj_info.get_fields(): field_name = escape_identifier(field.name) attr = FieldAttribute(field_name, field) setattr(cls, field_name, attr) # Add methods for method_info in obj_info.get_methods(): # we implement most of the base object ourself add_method(method_info, cls, dont_replace=cls is Object) # VFuncs for vfunc_info in obj_info.get_vfuncs(): add_method(vfunc_info, cls, virtual=True) cs_info = obj_info.get_class_struct() if cs_info: class_struct = import_attribute(cs_info.namespace, cs_info.name) else: class_struct = None # XXX ^ 2 def get_class_struct(cls, type_=None): """Returns the class struct casted to the passed type""" if type_ is None: type_ = class_struct if type_ is None: return None ptr = cls.__gtype__._type.class_ref() return type_._from_pointer(ptr) setattr(cls, "_get_class_struct", classmethod(get_class_struct)) return cls
python
def ObjectAttribute(obj_info): """Creates a GObject class. It inherits from the base class and all interfaces it implements. """ if obj_info.name == "Object" and obj_info.namespace == "GObject": cls = Object else: # Get the parent class parent_obj = obj_info.get_parent() if parent_obj: attr = import_attribute(parent_obj.namespace, parent_obj.name) bases = (attr,) else: bases = (object,) # Get all object interfaces ifaces = [] for interface in obj_info.get_interfaces(): attr = import_attribute(interface.namespace, interface.name) # only add interfaces if the base classes don't have it for base in bases: if attr in base.__mro__: break else: ifaces.append(attr) # Combine them to a base class list if ifaces: bases = tuple(list(bases) + ifaces) # Create a new class cls = type(obj_info.name, bases, dict()) cls.__module__ = obj_info.namespace # Set root to unowned= False and InitiallyUnowned=True if obj_info.namespace == "GObject": if obj_info.name == "InitiallyUnowned": cls._unowned = True elif obj_info.name == "Object": cls._unowned = False # GType cls.__gtype__ = PGType(obj_info.g_type) if not obj_info.fundamental: # Constructor cache cls._constructors = {} # Properties setattr(cls, PROPS_NAME, PropertyAttribute(obj_info)) # Signals cls.signals = SignalsAttribute(obj_info) # Signals cls.__sigs__ = {} for sig_info in obj_info.get_signals(): signal_name = sig_info.name cls.__sigs__[signal_name] = sig_info # Add constants for constant in obj_info.get_constants(): constant_name = constant.name attr = ConstantAttribute(constant) setattr(cls, constant_name, attr) # Fields for field in obj_info.get_fields(): field_name = escape_identifier(field.name) attr = FieldAttribute(field_name, field) setattr(cls, field_name, attr) # Add methods for method_info in obj_info.get_methods(): # we implement most of the base object ourself add_method(method_info, cls, dont_replace=cls is Object) # VFuncs for vfunc_info in obj_info.get_vfuncs(): add_method(vfunc_info, cls, virtual=True) cs_info = obj_info.get_class_struct() if cs_info: class_struct = import_attribute(cs_info.namespace, cs_info.name) else: class_struct = None # XXX ^ 2 def get_class_struct(cls, type_=None): """Returns the class struct casted to the passed type""" if type_ is None: type_ = class_struct if type_ is None: return None ptr = cls.__gtype__._type.class_ref() return type_._from_pointer(ptr) setattr(cls, "_get_class_struct", classmethod(get_class_struct)) return cls
[ "def", "ObjectAttribute", "(", "obj_info", ")", ":", "if", "obj_info", ".", "name", "==", "\"Object\"", "and", "obj_info", ".", "namespace", "==", "\"GObject\"", ":", "cls", "=", "Object", "else", ":", "# Get the parent class", "parent_obj", "=", "obj_info", ".", "get_parent", "(", ")", "if", "parent_obj", ":", "attr", "=", "import_attribute", "(", "parent_obj", ".", "namespace", ",", "parent_obj", ".", "name", ")", "bases", "=", "(", "attr", ",", ")", "else", ":", "bases", "=", "(", "object", ",", ")", "# Get all object interfaces", "ifaces", "=", "[", "]", "for", "interface", "in", "obj_info", ".", "get_interfaces", "(", ")", ":", "attr", "=", "import_attribute", "(", "interface", ".", "namespace", ",", "interface", ".", "name", ")", "# only add interfaces if the base classes don't have it", "for", "base", "in", "bases", ":", "if", "attr", "in", "base", ".", "__mro__", ":", "break", "else", ":", "ifaces", ".", "append", "(", "attr", ")", "# Combine them to a base class list", "if", "ifaces", ":", "bases", "=", "tuple", "(", "list", "(", "bases", ")", "+", "ifaces", ")", "# Create a new class", "cls", "=", "type", "(", "obj_info", ".", "name", ",", "bases", ",", "dict", "(", ")", ")", "cls", ".", "__module__", "=", "obj_info", ".", "namespace", "# Set root to unowned= False and InitiallyUnowned=True", "if", "obj_info", ".", "namespace", "==", "\"GObject\"", ":", "if", "obj_info", ".", "name", "==", "\"InitiallyUnowned\"", ":", "cls", ".", "_unowned", "=", "True", "elif", "obj_info", ".", "name", "==", "\"Object\"", ":", "cls", ".", "_unowned", "=", "False", "# GType", "cls", ".", "__gtype__", "=", "PGType", "(", "obj_info", ".", "g_type", ")", "if", "not", "obj_info", ".", "fundamental", ":", "# Constructor cache", "cls", ".", "_constructors", "=", "{", "}", "# Properties", "setattr", "(", "cls", ",", "PROPS_NAME", ",", "PropertyAttribute", "(", "obj_info", ")", ")", "# Signals", "cls", ".", "signals", "=", "SignalsAttribute", "(", "obj_info", ")", "# Signals", "cls", ".", "__sigs__", "=", "{", "}", "for", "sig_info", "in", "obj_info", ".", "get_signals", "(", ")", ":", "signal_name", "=", "sig_info", ".", "name", "cls", ".", "__sigs__", "[", "signal_name", "]", "=", "sig_info", "# Add constants", "for", "constant", "in", "obj_info", ".", "get_constants", "(", ")", ":", "constant_name", "=", "constant", ".", "name", "attr", "=", "ConstantAttribute", "(", "constant", ")", "setattr", "(", "cls", ",", "constant_name", ",", "attr", ")", "# Fields", "for", "field", "in", "obj_info", ".", "get_fields", "(", ")", ":", "field_name", "=", "escape_identifier", "(", "field", ".", "name", ")", "attr", "=", "FieldAttribute", "(", "field_name", ",", "field", ")", "setattr", "(", "cls", ",", "field_name", ",", "attr", ")", "# Add methods", "for", "method_info", "in", "obj_info", ".", "get_methods", "(", ")", ":", "# we implement most of the base object ourself", "add_method", "(", "method_info", ",", "cls", ",", "dont_replace", "=", "cls", "is", "Object", ")", "# VFuncs", "for", "vfunc_info", "in", "obj_info", ".", "get_vfuncs", "(", ")", ":", "add_method", "(", "vfunc_info", ",", "cls", ",", "virtual", "=", "True", ")", "cs_info", "=", "obj_info", ".", "get_class_struct", "(", ")", "if", "cs_info", ":", "class_struct", "=", "import_attribute", "(", "cs_info", ".", "namespace", ",", "cs_info", ".", "name", ")", "else", ":", "class_struct", "=", "None", "# XXX ^ 2", "def", "get_class_struct", "(", "cls", ",", "type_", "=", "None", ")", ":", "\"\"\"Returns the class struct casted to the passed type\"\"\"", "if", "type_", "is", "None", ":", "type_", "=", "class_struct", "if", "type_", "is", "None", ":", "return", "None", "ptr", "=", "cls", ".", "__gtype__", ".", "_type", ".", "class_ref", "(", ")", "return", "type_", ".", "_from_pointer", "(", "ptr", ")", "setattr", "(", "cls", ",", "\"_get_class_struct\"", ",", "classmethod", "(", "get_class_struct", ")", ")", "return", "cls" ]
Creates a GObject class. It inherits from the base class and all interfaces it implements.
[ "Creates", "a", "GObject", "class", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L414-L519
train
pygobject/pgi
pgi/obj.py
Object._generate_constructor
def _generate_constructor(cls, names): """Get a hopefully cache constructor""" cache = cls._constructors if names in cache: return cache[names] elif len(cache) > 3: cache.clear() func = generate_constructor(cls, names) cache[names] = func return func
python
def _generate_constructor(cls, names): """Get a hopefully cache constructor""" cache = cls._constructors if names in cache: return cache[names] elif len(cache) > 3: cache.clear() func = generate_constructor(cls, names) cache[names] = func return func
[ "def", "_generate_constructor", "(", "cls", ",", "names", ")", ":", "cache", "=", "cls", ".", "_constructors", "if", "names", "in", "cache", ":", "return", "cache", "[", "names", "]", "elif", "len", "(", "cache", ")", ">", "3", ":", "cache", ".", "clear", "(", ")", "func", "=", "generate_constructor", "(", "cls", ",", "names", ")", "cache", "[", "names", "]", "=", "func", "return", "func" ]
Get a hopefully cache constructor
[ "Get", "a", "hopefully", "cache", "constructor" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L55-L66
train
pygobject/pgi
pgi/obj.py
Object.set_property
def set_property(self, name, value): """set_property(property_name: str, value: object) Set property *property_name* to *value*. """ if not hasattr(self.props, name): raise TypeError("Unknown property: %r" % name) setattr(self.props, name, value)
python
def set_property(self, name, value): """set_property(property_name: str, value: object) Set property *property_name* to *value*. """ if not hasattr(self.props, name): raise TypeError("Unknown property: %r" % name) setattr(self.props, name, value)
[ "def", "set_property", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "hasattr", "(", "self", ".", "props", ",", "name", ")", ":", "raise", "TypeError", "(", "\"Unknown property: %r\"", "%", "name", ")", "setattr", "(", "self", ".", "props", ",", "name", ",", "value", ")" ]
set_property(property_name: str, value: object) Set property *property_name* to *value*.
[ "set_property", "(", "property_name", ":", "str", "value", ":", "object", ")" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L68-L76
train
pygobject/pgi
pgi/obj.py
Object.get_property
def get_property(self, name): """get_property(property_name: str) -> object Retrieves a property value. """ if not hasattr(self.props, name): raise TypeError("Unknown property: %r" % name) return getattr(self.props, name)
python
def get_property(self, name): """get_property(property_name: str) -> object Retrieves a property value. """ if not hasattr(self.props, name): raise TypeError("Unknown property: %r" % name) return getattr(self.props, name)
[ "def", "get_property", "(", "self", ",", "name", ")", ":", "if", "not", "hasattr", "(", "self", ".", "props", ",", "name", ")", ":", "raise", "TypeError", "(", "\"Unknown property: %r\"", "%", "name", ")", "return", "getattr", "(", "self", ".", "props", ",", "name", ")" ]
get_property(property_name: str) -> object Retrieves a property value.
[ "get_property", "(", "property_name", ":", "str", ")", "-", ">", "object" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L78-L86
train
pygobject/pgi
pgi/obj.py
Object.connect
def connect(self, detailed_signal, handler, *args): """connect(detailed_signal: str, handler: function, *args) -> handler_id: int The connect() method adds a function or method (handler) to the end of the list of signal handlers for the named detailed_signal but before the default class signal handler. An optional set of parameters may be specified after the handler parameter. These will all be passed to the signal handler when invoked. For example if a function handler was connected to a signal using:: handler_id = object.connect("signal_name", handler, arg1, arg2, arg3) The handler should be defined as:: def handler(object, arg1, arg2, arg3): A method handler connected to a signal using:: handler_id = object.connect("signal_name", self.handler, arg1, arg2) requires an additional argument when defined:: def handler(self, object, arg1, arg2) A TypeError exception is raised if detailed_signal identifies a signal name that is not associated with the object. """ return self.__connect(0, detailed_signal, handler, *args)
python
def connect(self, detailed_signal, handler, *args): """connect(detailed_signal: str, handler: function, *args) -> handler_id: int The connect() method adds a function or method (handler) to the end of the list of signal handlers for the named detailed_signal but before the default class signal handler. An optional set of parameters may be specified after the handler parameter. These will all be passed to the signal handler when invoked. For example if a function handler was connected to a signal using:: handler_id = object.connect("signal_name", handler, arg1, arg2, arg3) The handler should be defined as:: def handler(object, arg1, arg2, arg3): A method handler connected to a signal using:: handler_id = object.connect("signal_name", self.handler, arg1, arg2) requires an additional argument when defined:: def handler(self, object, arg1, arg2) A TypeError exception is raised if detailed_signal identifies a signal name that is not associated with the object. """ return self.__connect(0, detailed_signal, handler, *args)
[ "def", "connect", "(", "self", ",", "detailed_signal", ",", "handler", ",", "*", "args", ")", ":", "return", "self", ".", "__connect", "(", "0", ",", "detailed_signal", ",", "handler", ",", "*", "args", ")" ]
connect(detailed_signal: str, handler: function, *args) -> handler_id: int The connect() method adds a function or method (handler) to the end of the list of signal handlers for the named detailed_signal but before the default class signal handler. An optional set of parameters may be specified after the handler parameter. These will all be passed to the signal handler when invoked. For example if a function handler was connected to a signal using:: handler_id = object.connect("signal_name", handler, arg1, arg2, arg3) The handler should be defined as:: def handler(object, arg1, arg2, arg3): A method handler connected to a signal using:: handler_id = object.connect("signal_name", self.handler, arg1, arg2) requires an additional argument when defined:: def handler(self, object, arg1, arg2) A TypeError exception is raised if detailed_signal identifies a signal name that is not associated with the object.
[ "connect", "(", "detailed_signal", ":", "str", "handler", ":", "function", "*", "args", ")", "-", ">", "handler_id", ":", "int" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L127-L156
train
pygobject/pgi
pgi/obj.py
Object.connect_after
def connect_after(self, detailed_signal, handler, *args): """connect_after(detailed_signal: str, handler: function, *args) -> handler_id: int The connect_after() method is similar to the connect() method except that the handler is added to the signal handler list after the default class signal handler. Otherwise the details of handler definition and invocation are the same. """ flags = GConnectFlags.CONNECT_AFTER return self.__connect(flags, detailed_signal, handler, *args)
python
def connect_after(self, detailed_signal, handler, *args): """connect_after(detailed_signal: str, handler: function, *args) -> handler_id: int The connect_after() method is similar to the connect() method except that the handler is added to the signal handler list after the default class signal handler. Otherwise the details of handler definition and invocation are the same. """ flags = GConnectFlags.CONNECT_AFTER return self.__connect(flags, detailed_signal, handler, *args)
[ "def", "connect_after", "(", "self", ",", "detailed_signal", ",", "handler", ",", "*", "args", ")", ":", "flags", "=", "GConnectFlags", ".", "CONNECT_AFTER", "return", "self", ".", "__connect", "(", "flags", ",", "detailed_signal", ",", "handler", ",", "*", "args", ")" ]
connect_after(detailed_signal: str, handler: function, *args) -> handler_id: int The connect_after() method is similar to the connect() method except that the handler is added to the signal handler list after the default class signal handler. Otherwise the details of handler definition and invocation are the same.
[ "connect_after", "(", "detailed_signal", ":", "str", "handler", ":", "function", "*", "args", ")", "-", ">", "handler_id", ":", "int" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L158-L168
train
pygobject/pgi
pgi/clib/gir/gibaseinfo.py
GIBaseInfo._take_ownership
def _take_ownership(self): """Make the Python instance take ownership of the GIBaseInfo. i.e. unref if the python instance gets gc'ed. """ if self: ptr = cast(self.value, GIBaseInfo) _UnrefFinalizer.track(self, ptr) self.__owns = True
python
def _take_ownership(self): """Make the Python instance take ownership of the GIBaseInfo. i.e. unref if the python instance gets gc'ed. """ if self: ptr = cast(self.value, GIBaseInfo) _UnrefFinalizer.track(self, ptr) self.__owns = True
[ "def", "_take_ownership", "(", "self", ")", ":", "if", "self", ":", "ptr", "=", "cast", "(", "self", ".", "value", ",", "GIBaseInfo", ")", "_UnrefFinalizer", ".", "track", "(", "self", ",", "ptr", ")", "self", ".", "__owns", "=", "True" ]
Make the Python instance take ownership of the GIBaseInfo. i.e. unref if the python instance gets gc'ed.
[ "Make", "the", "Python", "instance", "take", "ownership", "of", "the", "GIBaseInfo", ".", "i", ".", "e", ".", "unref", "if", "the", "python", "instance", "gets", "gc", "ed", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/gir/gibaseinfo.py#L61-L69
train
pygobject/pgi
pgi/clib/gir/gibaseinfo.py
GIBaseInfo._cast
def _cast(cls, base_info, take_ownership=True): """Casts a GIBaseInfo instance to the right sub type. The original GIBaseInfo can't have ownership. Will take ownership. """ type_value = base_info.type.value try: new_obj = cast(base_info, cls.__types[type_value]) except KeyError: new_obj = base_info if take_ownership: assert not base_info.__owns new_obj._take_ownership() return new_obj
python
def _cast(cls, base_info, take_ownership=True): """Casts a GIBaseInfo instance to the right sub type. The original GIBaseInfo can't have ownership. Will take ownership. """ type_value = base_info.type.value try: new_obj = cast(base_info, cls.__types[type_value]) except KeyError: new_obj = base_info if take_ownership: assert not base_info.__owns new_obj._take_ownership() return new_obj
[ "def", "_cast", "(", "cls", ",", "base_info", ",", "take_ownership", "=", "True", ")", ":", "type_value", "=", "base_info", ".", "type", ".", "value", "try", ":", "new_obj", "=", "cast", "(", "base_info", ",", "cls", ".", "__types", "[", "type_value", "]", ")", "except", "KeyError", ":", "new_obj", "=", "base_info", "if", "take_ownership", ":", "assert", "not", "base_info", ".", "__owns", "new_obj", ".", "_take_ownership", "(", ")", "return", "new_obj" ]
Casts a GIBaseInfo instance to the right sub type. The original GIBaseInfo can't have ownership. Will take ownership.
[ "Casts", "a", "GIBaseInfo", "instance", "to", "the", "right", "sub", "type", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/gir/gibaseinfo.py#L72-L89
train
pygobject/pgi
pgi/util.py
decode_return
def decode_return(codec="ascii"): """Decodes the return value of it isn't None""" def outer(f): def wrap(*args, **kwargs): res = f(*args, **kwargs) if res is not None: return res.decode(codec) return res return wrap return outer
python
def decode_return(codec="ascii"): """Decodes the return value of it isn't None""" def outer(f): def wrap(*args, **kwargs): res = f(*args, **kwargs) if res is not None: return res.decode(codec) return res return wrap return outer
[ "def", "decode_return", "(", "codec", "=", "\"ascii\"", ")", ":", "def", "outer", "(", "f", ")", ":", "def", "wrap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "res", "is", "not", "None", ":", "return", "res", ".", "decode", "(", "codec", ")", "return", "res", "return", "wrap", "return", "outer" ]
Decodes the return value of it isn't None
[ "Decodes", "the", "return", "value", "of", "it", "isn", "t", "None" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L27-L37
train
pygobject/pgi
pgi/util.py
load_ctypes_library
def load_ctypes_library(name): """Takes a library name and calls find_library in case loading fails, since some girs don't include the real .so name. Raises OSError like LoadLibrary if loading fails. e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix """ try: return cdll.LoadLibrary(name) except OSError: name = find_library(name) if name is None: raise return cdll.LoadLibrary(name)
python
def load_ctypes_library(name): """Takes a library name and calls find_library in case loading fails, since some girs don't include the real .so name. Raises OSError like LoadLibrary if loading fails. e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix """ try: return cdll.LoadLibrary(name) except OSError: name = find_library(name) if name is None: raise return cdll.LoadLibrary(name)
[ "def", "load_ctypes_library", "(", "name", ")", ":", "try", ":", "return", "cdll", ".", "LoadLibrary", "(", "name", ")", "except", "OSError", ":", "name", "=", "find_library", "(", "name", ")", "if", "name", "is", "None", ":", "raise", "return", "cdll", ".", "LoadLibrary", "(", "name", ")" ]
Takes a library name and calls find_library in case loading fails, since some girs don't include the real .so name. Raises OSError like LoadLibrary if loading fails. e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix
[ "Takes", "a", "library", "name", "and", "calls", "find_library", "in", "case", "loading", "fails", "since", "some", "girs", "don", "t", "include", "the", "real", ".", "so", "name", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L50-L65
train
pygobject/pgi
pgi/util.py
escape_identifier
def escape_identifier(text, reg=KWD_RE): """Escape partial C identifiers so they can be used as attributes/arguments""" # see http://docs.python.org/reference/lexical_analysis.html#identifiers if not text: return "_" if text[0].isdigit(): text = "_" + text return reg.sub(r"\1_", text)
python
def escape_identifier(text, reg=KWD_RE): """Escape partial C identifiers so they can be used as attributes/arguments""" # see http://docs.python.org/reference/lexical_analysis.html#identifiers if not text: return "_" if text[0].isdigit(): text = "_" + text return reg.sub(r"\1_", text)
[ "def", "escape_identifier", "(", "text", ",", "reg", "=", "KWD_RE", ")", ":", "# see http://docs.python.org/reference/lexical_analysis.html#identifiers", "if", "not", "text", ":", "return", "\"_\"", "if", "text", "[", "0", "]", ".", "isdigit", "(", ")", ":", "text", "=", "\"_\"", "+", "text", "return", "reg", ".", "sub", "(", "r\"\\1_\"", ",", "text", ")" ]
Escape partial C identifiers so they can be used as attributes/arguments
[ "Escape", "partial", "C", "identifiers", "so", "they", "can", "be", "used", "as", "attributes", "/", "arguments" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L226-L235
train
pygobject/pgi
pgi/util.py
cache_return
def cache_return(func): """Cache the return value of a function without arguments""" _cache = [] def wrap(): if not _cache: _cache.append(func()) return _cache[0] return wrap
python
def cache_return(func): """Cache the return value of a function without arguments""" _cache = [] def wrap(): if not _cache: _cache.append(func()) return _cache[0] return wrap
[ "def", "cache_return", "(", "func", ")", ":", "_cache", "=", "[", "]", "def", "wrap", "(", ")", ":", "if", "not", "_cache", ":", "_cache", ".", "append", "(", "func", "(", ")", ")", "return", "_cache", "[", "0", "]", "return", "wrap" ]
Cache the return value of a function without arguments
[ "Cache", "the", "return", "value", "of", "a", "function", "without", "arguments" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L263-L272
train
pygobject/pgi
pgi/util.py
InfoIterWrapper.lookup_name_fast
def lookup_name_fast(self, name): """Might return a struct""" if name in self.__names: return self.__names[name] count = self.__get_count_cached() lo = 0 hi = count while lo < hi: mid = (lo + hi) // 2 if self.__get_name_cached(mid) < name: lo = mid + 1 else: hi = mid if lo != count and self.__get_name_cached(lo) == name: return self.__get_info_cached(lo)
python
def lookup_name_fast(self, name): """Might return a struct""" if name in self.__names: return self.__names[name] count = self.__get_count_cached() lo = 0 hi = count while lo < hi: mid = (lo + hi) // 2 if self.__get_name_cached(mid) < name: lo = mid + 1 else: hi = mid if lo != count and self.__get_name_cached(lo) == name: return self.__get_info_cached(lo)
[ "def", "lookup_name_fast", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "__names", ":", "return", "self", ".", "__names", "[", "name", "]", "count", "=", "self", ".", "__get_count_cached", "(", ")", "lo", "=", "0", "hi", "=", "count", "while", "lo", "<", "hi", ":", "mid", "=", "(", "lo", "+", "hi", ")", "//", "2", "if", "self", ".", "__get_name_cached", "(", "mid", ")", "<", "name", ":", "lo", "=", "mid", "+", "1", "else", ":", "hi", "=", "mid", "if", "lo", "!=", "count", "and", "self", ".", "__get_name_cached", "(", "lo", ")", "==", "name", ":", "return", "self", ".", "__get_info_cached", "(", "lo", ")" ]
Might return a struct
[ "Might", "return", "a", "struct" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L115-L132
train
pygobject/pgi
pgi/util.py
InfoIterWrapper.lookup_name_slow
def lookup_name_slow(self, name): """Returns a struct if one exists""" for index in xrange(self.__get_count_cached()): if self.__get_name_cached(index) == name: return self.__get_info_cached(index)
python
def lookup_name_slow(self, name): """Returns a struct if one exists""" for index in xrange(self.__get_count_cached()): if self.__get_name_cached(index) == name: return self.__get_info_cached(index)
[ "def", "lookup_name_slow", "(", "self", ",", "name", ")", ":", "for", "index", "in", "xrange", "(", "self", ".", "__get_count_cached", "(", ")", ")", ":", "if", "self", ".", "__get_name_cached", "(", "index", ")", "==", "name", ":", "return", "self", ".", "__get_info_cached", "(", "index", ")" ]
Returns a struct if one exists
[ "Returns", "a", "struct", "if", "one", "exists" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L134-L139
train
pygobject/pgi
pgi/util.py
InfoIterWrapper.lookup_name
def lookup_name(self, name): """Returns a struct if one exists""" try: info = self._get_by_name(self._source, name) except NotImplementedError: pass else: if info: return info return info = self.lookup_name_fast(name) if info: return info return self.lookup_name_slow(name)
python
def lookup_name(self, name): """Returns a struct if one exists""" try: info = self._get_by_name(self._source, name) except NotImplementedError: pass else: if info: return info return info = self.lookup_name_fast(name) if info: return info return self.lookup_name_slow(name)
[ "def", "lookup_name", "(", "self", ",", "name", ")", ":", "try", ":", "info", "=", "self", ".", "_get_by_name", "(", "self", ".", "_source", ",", "name", ")", "except", "NotImplementedError", ":", "pass", "else", ":", "if", "info", ":", "return", "info", "return", "info", "=", "self", ".", "lookup_name_fast", "(", "name", ")", "if", "info", ":", "return", "info", "return", "self", ".", "lookup_name_slow", "(", "name", ")" ]
Returns a struct if one exists
[ "Returns", "a", "struct", "if", "one", "exists" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L141-L156
train
pygobject/pgi
pgi/util.py
ResultTuple._new_type
def _new_type(cls, args): """Creates a new class similar to namedtuple. Pass a list of field names or None for no field name. >>> x = ResultTuple._new_type([None, "bar"]) >>> x((1, 3)) ResultTuple(1, bar=3) """ fformat = ["%r" if f is None else "%s=%%r" % f for f in args] fformat = "(%s)" % ", ".join(fformat) class _ResultTuple(cls): __slots__ = () _fformat = fformat if args: for i, a in enumerate(args): if a is not None: vars()[a] = property(itemgetter(i)) del i, a return _ResultTuple
python
def _new_type(cls, args): """Creates a new class similar to namedtuple. Pass a list of field names or None for no field name. >>> x = ResultTuple._new_type([None, "bar"]) >>> x((1, 3)) ResultTuple(1, bar=3) """ fformat = ["%r" if f is None else "%s=%%r" % f for f in args] fformat = "(%s)" % ", ".join(fformat) class _ResultTuple(cls): __slots__ = () _fformat = fformat if args: for i, a in enumerate(args): if a is not None: vars()[a] = property(itemgetter(i)) del i, a return _ResultTuple
[ "def", "_new_type", "(", "cls", ",", "args", ")", ":", "fformat", "=", "[", "\"%r\"", "if", "f", "is", "None", "else", "\"%s=%%r\"", "%", "f", "for", "f", "in", "args", "]", "fformat", "=", "\"(%s)\"", "%", "\", \"", ".", "join", "(", "fformat", ")", "class", "_ResultTuple", "(", "cls", ")", ":", "__slots__", "=", "(", ")", "_fformat", "=", "fformat", "if", "args", ":", "for", "i", ",", "a", "in", "enumerate", "(", "args", ")", ":", "if", "a", "is", "not", "None", ":", "vars", "(", ")", "[", "a", "]", "=", "property", "(", "itemgetter", "(", "i", ")", ")", "del", "i", ",", "a", "return", "_ResultTuple" ]
Creates a new class similar to namedtuple. Pass a list of field names or None for no field name. >>> x = ResultTuple._new_type([None, "bar"]) >>> x((1, 3)) ResultTuple(1, bar=3)
[ "Creates", "a", "new", "class", "similar", "to", "namedtuple", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/util.py#L320-L342
train
pygobject/pgi
pgi/overrides/GObject.py
signal_list_names
def signal_list_names(type_): """Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal names :rtype: :obj:`list` """ ids = signal_list_ids(type_) return tuple(GObjectModule.signal_name(i) for i in ids)
python
def signal_list_names(type_): """Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal names :rtype: :obj:`list` """ ids = signal_list_ids(type_) return tuple(GObjectModule.signal_name(i) for i in ids)
[ "def", "signal_list_names", "(", "type_", ")", ":", "ids", "=", "signal_list_ids", "(", "type_", ")", "return", "tuple", "(", "GObjectModule", ".", "signal_name", "(", "i", ")", "for", "i", "in", "ids", ")" ]
Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal names :rtype: :obj:`list`
[ "Returns", "a", "list", "of", "signal", "names", "for", "the", "given", "type" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GObject.py#L392-L402
train
pygobject/pgi
pgi/overrides/GObject.py
signal_handler_block
def signal_handler_block(obj, handler_id): """Blocks the signal handler from being invoked until handler_unblock() is called. :param GObject.Object obj: Object instance to block handlers for. :param int handler_id: Id of signal to block. :returns: A context manager which optionally can be used to automatically unblock the handler: .. code-block:: python with GObject.signal_handler_block(obj, id): pass """ GObjectModule.signal_handler_block(obj, handler_id) return _HandlerBlockManager(obj, handler_id)
python
def signal_handler_block(obj, handler_id): """Blocks the signal handler from being invoked until handler_unblock() is called. :param GObject.Object obj: Object instance to block handlers for. :param int handler_id: Id of signal to block. :returns: A context manager which optionally can be used to automatically unblock the handler: .. code-block:: python with GObject.signal_handler_block(obj, id): pass """ GObjectModule.signal_handler_block(obj, handler_id) return _HandlerBlockManager(obj, handler_id)
[ "def", "signal_handler_block", "(", "obj", ",", "handler_id", ")", ":", "GObjectModule", ".", "signal_handler_block", "(", "obj", ",", "handler_id", ")", "return", "_HandlerBlockManager", "(", "obj", ",", "handler_id", ")" ]
Blocks the signal handler from being invoked until handler_unblock() is called. :param GObject.Object obj: Object instance to block handlers for. :param int handler_id: Id of signal to block. :returns: A context manager which optionally can be used to automatically unblock the handler: .. code-block:: python with GObject.signal_handler_block(obj, id): pass
[ "Blocks", "the", "signal", "handler", "from", "being", "invoked", "until", "handler_unblock", "()", "is", "called", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GObject.py#L458-L476
train
pygobject/pgi
pgi/overrides/GObject.py
signal_parse_name
def signal_parse_name(detailed_signal, itype, force_detail_quark): """Parse a detailed signal name into (signal_id, detail). :param str detailed_signal: Signal name which can include detail. For example: "notify:prop_name" :returns: Tuple of (signal_id, detail) :raises ValueError: If the given signal is unknown. """ res, signal_id, detail = GObjectModule.signal_parse_name(detailed_signal, itype, force_detail_quark) if res: return signal_id, detail else: raise ValueError('%s: unknown signal name: %s' % (itype, detailed_signal))
python
def signal_parse_name(detailed_signal, itype, force_detail_quark): """Parse a detailed signal name into (signal_id, detail). :param str detailed_signal: Signal name which can include detail. For example: "notify:prop_name" :returns: Tuple of (signal_id, detail) :raises ValueError: If the given signal is unknown. """ res, signal_id, detail = GObjectModule.signal_parse_name(detailed_signal, itype, force_detail_quark) if res: return signal_id, detail else: raise ValueError('%s: unknown signal name: %s' % (itype, detailed_signal))
[ "def", "signal_parse_name", "(", "detailed_signal", ",", "itype", ",", "force_detail_quark", ")", ":", "res", ",", "signal_id", ",", "detail", "=", "GObjectModule", ".", "signal_parse_name", "(", "detailed_signal", ",", "itype", ",", "force_detail_quark", ")", "if", "res", ":", "return", "signal_id", ",", "detail", "else", ":", "raise", "ValueError", "(", "'%s: unknown signal name: %s'", "%", "(", "itype", ",", "detailed_signal", ")", ")" ]
Parse a detailed signal name into (signal_id, detail). :param str detailed_signal: Signal name which can include detail. For example: "notify:prop_name" :returns: Tuple of (signal_id, detail) :raises ValueError: If the given signal is unknown.
[ "Parse", "a", "detailed", "signal", "name", "into", "(", "signal_id", "detail", ")", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GObject.py#L481-L497
train
pygobject/pgi
pgi/clib/_utils.py
find_library
def find_library(name, cached=True, internal=True): """ cached: Return a new instance internal: return a shared instance that's not the ctypes cached one """ # a new one if not cached: return cdll.LoadLibrary(_so_mapping[name]) # from the shared internal set or a new one if internal: if name not in _internal: _internal[name] = cdll.LoadLibrary(_so_mapping[name]) return _internal[name] # a shared one return getattr(cdll, _so_mapping[name])
python
def find_library(name, cached=True, internal=True): """ cached: Return a new instance internal: return a shared instance that's not the ctypes cached one """ # a new one if not cached: return cdll.LoadLibrary(_so_mapping[name]) # from the shared internal set or a new one if internal: if name not in _internal: _internal[name] = cdll.LoadLibrary(_so_mapping[name]) return _internal[name] # a shared one return getattr(cdll, _so_mapping[name])
[ "def", "find_library", "(", "name", ",", "cached", "=", "True", ",", "internal", "=", "True", ")", ":", "# a new one", "if", "not", "cached", ":", "return", "cdll", ".", "LoadLibrary", "(", "_so_mapping", "[", "name", "]", ")", "# from the shared internal set or a new one", "if", "internal", ":", "if", "name", "not", "in", "_internal", ":", "_internal", "[", "name", "]", "=", "cdll", ".", "LoadLibrary", "(", "_so_mapping", "[", "name", "]", ")", "return", "_internal", "[", "name", "]", "# a shared one", "return", "getattr", "(", "cdll", ",", "_so_mapping", "[", "name", "]", ")" ]
cached: Return a new instance internal: return a shared instance that's not the ctypes cached one
[ "cached", ":", "Return", "a", "new", "instance", "internal", ":", "return", "a", "shared", "instance", "that", "s", "not", "the", "ctypes", "cached", "one" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/_utils.py#L86-L103
train
pygobject/pgi
pgi/clib/_utils.py
_BaseFinalizer.track
def track(cls, obj, ptr): """ Track an object which needs destruction when it is garbage collected. """ cls._objects.add(cls(obj, ptr))
python
def track(cls, obj, ptr): """ Track an object which needs destruction when it is garbage collected. """ cls._objects.add(cls(obj, ptr))
[ "def", "track", "(", "cls", ",", "obj", ",", "ptr", ")", ":", "cls", ".", "_objects", ".", "add", "(", "cls", "(", "obj", ",", "ptr", ")", ")" ]
Track an object which needs destruction when it is garbage collected.
[ "Track", "an", "object", "which", "needs", "destruction", "when", "it", "is", "garbage", "collected", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/_utils.py#L23-L27
train
pygobject/pgi
pgi/overrides/Gio.py
_DBusProxyMethodCall._unpack_result
def _unpack_result(klass, result): '''Convert a D-BUS return variant into an appropriate return value''' result = result.unpack() # to be compatible with standard Python behaviour, unbox # single-element tuples and return None for empty result tuples if len(result) == 1: result = result[0] elif len(result) == 0: result = None return result
python
def _unpack_result(klass, result): '''Convert a D-BUS return variant into an appropriate return value''' result = result.unpack() # to be compatible with standard Python behaviour, unbox # single-element tuples and return None for empty result tuples if len(result) == 1: result = result[0] elif len(result) == 0: result = None return result
[ "def", "_unpack_result", "(", "klass", ",", "result", ")", ":", "result", "=", "result", ".", "unpack", "(", ")", "# to be compatible with standard Python behaviour, unbox", "# single-element tuples and return None for empty result tuples", "if", "len", "(", "result", ")", "==", "1", ":", "result", "=", "result", "[", "0", "]", "elif", "len", "(", "result", ")", "==", "0", ":", "result", "=", "None", "return", "result" ]
Convert a D-BUS return variant into an appropriate return value
[ "Convert", "a", "D", "-", "BUS", "return", "variant", "into", "an", "appropriate", "return", "value" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/Gio.py#L173-L185
train
pygobject/pgi
pgi/properties.py
list_properties
def list_properties(type): """ :param type: a Python GObject instance or type that the signal is associated with :type type: :obj:`GObject.Object` :returns: a list of :obj:`GObject.ParamSpec` :rtype: [:obj:`GObject.ParamSpec`] Takes a GObject/GInterface subclass or a GType and returns a list of GParamSpecs for all properties of `type`. """ if isinstance(type, PGType): type = type.pytype from pgi.obj import Object, InterfaceBase if not issubclass(type, (Object, InterfaceBase)): raise TypeError("Must be a subclass of %s or %s" % (Object.__name__, InterfaceBase.__name__)) gparams = [] for key in dir(type.props): if not key.startswith("_"): gparams.append(getattr(type.props, key)) return gparams
python
def list_properties(type): """ :param type: a Python GObject instance or type that the signal is associated with :type type: :obj:`GObject.Object` :returns: a list of :obj:`GObject.ParamSpec` :rtype: [:obj:`GObject.ParamSpec`] Takes a GObject/GInterface subclass or a GType and returns a list of GParamSpecs for all properties of `type`. """ if isinstance(type, PGType): type = type.pytype from pgi.obj import Object, InterfaceBase if not issubclass(type, (Object, InterfaceBase)): raise TypeError("Must be a subclass of %s or %s" % (Object.__name__, InterfaceBase.__name__)) gparams = [] for key in dir(type.props): if not key.startswith("_"): gparams.append(getattr(type.props, key)) return gparams
[ "def", "list_properties", "(", "type", ")", ":", "if", "isinstance", "(", "type", ",", "PGType", ")", ":", "type", "=", "type", ".", "pytype", "from", "pgi", ".", "obj", "import", "Object", ",", "InterfaceBase", "if", "not", "issubclass", "(", "type", ",", "(", "Object", ",", "InterfaceBase", ")", ")", ":", "raise", "TypeError", "(", "\"Must be a subclass of %s or %s\"", "%", "(", "Object", ".", "__name__", ",", "InterfaceBase", ".", "__name__", ")", ")", "gparams", "=", "[", "]", "for", "key", "in", "dir", "(", "type", ".", "props", ")", ":", "if", "not", "key", ".", "startswith", "(", "\"_\"", ")", ":", "gparams", ".", "append", "(", "getattr", "(", "type", ".", "props", ",", "key", ")", ")", "return", "gparams" ]
:param type: a Python GObject instance or type that the signal is associated with :type type: :obj:`GObject.Object` :returns: a list of :obj:`GObject.ParamSpec` :rtype: [:obj:`GObject.ParamSpec`] Takes a GObject/GInterface subclass or a GType and returns a list of GParamSpecs for all properties of `type`.
[ ":", "param", "type", ":", "a", "Python", "GObject", "instance", "or", "type", "that", "the", "signal", "is", "associated", "with", ":", "type", "type", ":", ":", "obj", ":", "GObject", ".", "Object" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/properties.py#L282-L307
train
pygobject/pgi
pgi/overrides/__init__.py
load_overrides
def load_overrides(introspection_module): """Loads overrides for an introspection module. Either returns the same module again in case there are no overrides or a proxy module including overrides. Doesn't cache the result. """ namespace = introspection_module.__name__.rsplit(".", 1)[-1] module_keys = [prefix + "." + namespace for prefix in const.PREFIX] # We use sys.modules so overrides can import from gi.repository # but restore everything at the end so this doesn't have any side effects for module_key in module_keys: has_old = module_key in sys.modules old_module = sys.modules.get(module_key) # Create a new sub type, so we can separate descriptors like # _DeprecatedAttribute for each namespace. proxy_type = type(namespace + "ProxyModule", (OverridesProxyModule, ), {}) proxy = proxy_type(introspection_module) for module_key in module_keys: sys.modules[module_key] = proxy try: override_package_name = 'pgi.overrides.' + namespace # http://bugs.python.org/issue14710 try: override_loader = get_loader(override_package_name) except AttributeError: override_loader = None # Avoid checking for an ImportError, an override might # depend on a missing module thus causing an ImportError if override_loader is None: return introspection_module override_mod = importlib.import_module(override_package_name) finally: for module_key in module_keys: del sys.modules[module_key] if has_old: sys.modules[module_key] = old_module override_all = [] if hasattr(override_mod, "__all__"): override_all = override_mod.__all__ for var in override_all: try: item = getattr(override_mod, var) except (AttributeError, TypeError): # Gedit puts a non-string in __all__, so catch TypeError here continue # make sure new classes have a proper __module__ try: if item.__module__.split(".")[-1] == namespace: item.__module__ = namespace except AttributeError: pass setattr(proxy, var, item) # Replace deprecated module level attributes with a descriptor # which emits a warning when accessed. for attr, replacement in _deprecated_attrs.pop(namespace, []): try: value = getattr(proxy, attr) except AttributeError: raise AssertionError( "%s was set deprecated but wasn't added to __all__" % attr) delattr(proxy, attr) deprecated_attr = _DeprecatedAttribute( namespace, attr, value, replacement) setattr(proxy_type, attr, deprecated_attr) return proxy
python
def load_overrides(introspection_module): """Loads overrides for an introspection module. Either returns the same module again in case there are no overrides or a proxy module including overrides. Doesn't cache the result. """ namespace = introspection_module.__name__.rsplit(".", 1)[-1] module_keys = [prefix + "." + namespace for prefix in const.PREFIX] # We use sys.modules so overrides can import from gi.repository # but restore everything at the end so this doesn't have any side effects for module_key in module_keys: has_old = module_key in sys.modules old_module = sys.modules.get(module_key) # Create a new sub type, so we can separate descriptors like # _DeprecatedAttribute for each namespace. proxy_type = type(namespace + "ProxyModule", (OverridesProxyModule, ), {}) proxy = proxy_type(introspection_module) for module_key in module_keys: sys.modules[module_key] = proxy try: override_package_name = 'pgi.overrides.' + namespace # http://bugs.python.org/issue14710 try: override_loader = get_loader(override_package_name) except AttributeError: override_loader = None # Avoid checking for an ImportError, an override might # depend on a missing module thus causing an ImportError if override_loader is None: return introspection_module override_mod = importlib.import_module(override_package_name) finally: for module_key in module_keys: del sys.modules[module_key] if has_old: sys.modules[module_key] = old_module override_all = [] if hasattr(override_mod, "__all__"): override_all = override_mod.__all__ for var in override_all: try: item = getattr(override_mod, var) except (AttributeError, TypeError): # Gedit puts a non-string in __all__, so catch TypeError here continue # make sure new classes have a proper __module__ try: if item.__module__.split(".")[-1] == namespace: item.__module__ = namespace except AttributeError: pass setattr(proxy, var, item) # Replace deprecated module level attributes with a descriptor # which emits a warning when accessed. for attr, replacement in _deprecated_attrs.pop(namespace, []): try: value = getattr(proxy, attr) except AttributeError: raise AssertionError( "%s was set deprecated but wasn't added to __all__" % attr) delattr(proxy, attr) deprecated_attr = _DeprecatedAttribute( namespace, attr, value, replacement) setattr(proxy_type, attr, deprecated_attr) return proxy
[ "def", "load_overrides", "(", "introspection_module", ")", ":", "namespace", "=", "introspection_module", ".", "__name__", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "-", "1", "]", "module_keys", "=", "[", "prefix", "+", "\".\"", "+", "namespace", "for", "prefix", "in", "const", ".", "PREFIX", "]", "# We use sys.modules so overrides can import from gi.repository", "# but restore everything at the end so this doesn't have any side effects", "for", "module_key", "in", "module_keys", ":", "has_old", "=", "module_key", "in", "sys", ".", "modules", "old_module", "=", "sys", ".", "modules", ".", "get", "(", "module_key", ")", "# Create a new sub type, so we can separate descriptors like", "# _DeprecatedAttribute for each namespace.", "proxy_type", "=", "type", "(", "namespace", "+", "\"ProxyModule\"", ",", "(", "OverridesProxyModule", ",", ")", ",", "{", "}", ")", "proxy", "=", "proxy_type", "(", "introspection_module", ")", "for", "module_key", "in", "module_keys", ":", "sys", ".", "modules", "[", "module_key", "]", "=", "proxy", "try", ":", "override_package_name", "=", "'pgi.overrides.'", "+", "namespace", "# http://bugs.python.org/issue14710", "try", ":", "override_loader", "=", "get_loader", "(", "override_package_name", ")", "except", "AttributeError", ":", "override_loader", "=", "None", "# Avoid checking for an ImportError, an override might", "# depend on a missing module thus causing an ImportError", "if", "override_loader", "is", "None", ":", "return", "introspection_module", "override_mod", "=", "importlib", ".", "import_module", "(", "override_package_name", ")", "finally", ":", "for", "module_key", "in", "module_keys", ":", "del", "sys", ".", "modules", "[", "module_key", "]", "if", "has_old", ":", "sys", ".", "modules", "[", "module_key", "]", "=", "old_module", "override_all", "=", "[", "]", "if", "hasattr", "(", "override_mod", ",", "\"__all__\"", ")", ":", "override_all", "=", "override_mod", ".", "__all__", "for", "var", "in", "override_all", ":", "try", ":", "item", "=", "getattr", "(", "override_mod", ",", "var", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "# Gedit puts a non-string in __all__, so catch TypeError here", "continue", "# make sure new classes have a proper __module__", "try", ":", "if", "item", ".", "__module__", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "==", "namespace", ":", "item", ".", "__module__", "=", "namespace", "except", "AttributeError", ":", "pass", "setattr", "(", "proxy", ",", "var", ",", "item", ")", "# Replace deprecated module level attributes with a descriptor", "# which emits a warning when accessed.", "for", "attr", ",", "replacement", "in", "_deprecated_attrs", ".", "pop", "(", "namespace", ",", "[", "]", ")", ":", "try", ":", "value", "=", "getattr", "(", "proxy", ",", "attr", ")", "except", "AttributeError", ":", "raise", "AssertionError", "(", "\"%s was set deprecated but wasn't added to __all__\"", "%", "attr", ")", "delattr", "(", "proxy", ",", "attr", ")", "deprecated_attr", "=", "_DeprecatedAttribute", "(", "namespace", ",", "attr", ",", "value", ",", "replacement", ")", "setattr", "(", "proxy_type", ",", "attr", ",", "deprecated_attr", ")", "return", "proxy" ]
Loads overrides for an introspection module. Either returns the same module again in case there are no overrides or a proxy module including overrides. Doesn't cache the result.
[ "Loads", "overrides", "for", "an", "introspection", "module", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/__init__.py#L82-L160
train
pygobject/pgi
pgi/overrides/__init__.py
override
def override(klass): """Takes a override class or function and assigns it dunder arguments form the overidden one. """ namespace = klass.__module__.rsplit(".", 1)[-1] mod_name = const.PREFIX[-1] + "." + namespace module = sys.modules[mod_name] if isinstance(klass, types.FunctionType): def wrap(wrapped): setattr(module, klass.__name__, wrapped) return wrapped return wrap old_klass = klass.__mro__[1] name = old_klass.__name__ klass.__name__ = name klass.__module__ = old_klass.__module__ setattr(module, name, klass) return klass
python
def override(klass): """Takes a override class or function and assigns it dunder arguments form the overidden one. """ namespace = klass.__module__.rsplit(".", 1)[-1] mod_name = const.PREFIX[-1] + "." + namespace module = sys.modules[mod_name] if isinstance(klass, types.FunctionType): def wrap(wrapped): setattr(module, klass.__name__, wrapped) return wrapped return wrap old_klass = klass.__mro__[1] name = old_klass.__name__ klass.__name__ = name klass.__module__ = old_klass.__module__ setattr(module, name, klass) return klass
[ "def", "override", "(", "klass", ")", ":", "namespace", "=", "klass", ".", "__module__", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "-", "1", "]", "mod_name", "=", "const", ".", "PREFIX", "[", "-", "1", "]", "+", "\".\"", "+", "namespace", "module", "=", "sys", ".", "modules", "[", "mod_name", "]", "if", "isinstance", "(", "klass", ",", "types", ".", "FunctionType", ")", ":", "def", "wrap", "(", "wrapped", ")", ":", "setattr", "(", "module", ",", "klass", ".", "__name__", ",", "wrapped", ")", "return", "wrapped", "return", "wrap", "old_klass", "=", "klass", ".", "__mro__", "[", "1", "]", "name", "=", "old_klass", ".", "__name__", "klass", ".", "__name__", "=", "name", "klass", ".", "__module__", "=", "old_klass", ".", "__module__", "setattr", "(", "module", ",", "name", ",", "klass", ")", "return", "klass" ]
Takes a override class or function and assigns it dunder arguments form the overidden one.
[ "Takes", "a", "override", "class", "or", "function", "and", "assigns", "it", "dunder", "arguments", "form", "the", "overidden", "one", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/__init__.py#L163-L185
train
pygobject/pgi
pgi/overrides/__init__.py
deprecated
def deprecated(function, instead): """Mark a function deprecated so calling it issues a warning""" # skip for classes, breaks doc generation if not isinstance(function, types.FunctionType): return function @wraps(function) def wrap(*args, **kwargs): warnings.warn("Deprecated, use %s instead" % instead, PyGIDeprecationWarning) return function(*args, **kwargs) return wrap
python
def deprecated(function, instead): """Mark a function deprecated so calling it issues a warning""" # skip for classes, breaks doc generation if not isinstance(function, types.FunctionType): return function @wraps(function) def wrap(*args, **kwargs): warnings.warn("Deprecated, use %s instead" % instead, PyGIDeprecationWarning) return function(*args, **kwargs) return wrap
[ "def", "deprecated", "(", "function", ",", "instead", ")", ":", "# skip for classes, breaks doc generation", "if", "not", "isinstance", "(", "function", ",", "types", ".", "FunctionType", ")", ":", "return", "function", "@", "wraps", "(", "function", ")", "def", "wrap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"Deprecated, use %s instead\"", "%", "instead", ",", "PyGIDeprecationWarning", ")", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrap" ]
Mark a function deprecated so calling it issues a warning
[ "Mark", "a", "function", "deprecated", "so", "calling", "it", "issues", "a", "warning" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/__init__.py#L188-L201
train
pygobject/pgi
pgi/overrides/__init__.py
deprecated_attr
def deprecated_attr(namespace, attr, replacement): """Marks a module level attribute as deprecated. Accessing it will emit a PyGIDeprecationWarning warning. e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")`` accessing GObject.STATUS_FOO will emit: "GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead" :param str namespace: The namespace of the override this is called in. :param str namespace: The attribute name (which gets added to __all__). :param str replacement: The replacement text which will be included in the warning. """ _deprecated_attrs.setdefault(namespace, []).append((attr, replacement))
python
def deprecated_attr(namespace, attr, replacement): """Marks a module level attribute as deprecated. Accessing it will emit a PyGIDeprecationWarning warning. e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")`` accessing GObject.STATUS_FOO will emit: "GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead" :param str namespace: The namespace of the override this is called in. :param str namespace: The attribute name (which gets added to __all__). :param str replacement: The replacement text which will be included in the warning. """ _deprecated_attrs.setdefault(namespace, []).append((attr, replacement))
[ "def", "deprecated_attr", "(", "namespace", ",", "attr", ",", "replacement", ")", ":", "_deprecated_attrs", ".", "setdefault", "(", "namespace", ",", "[", "]", ")", ".", "append", "(", "(", "attr", ",", "replacement", ")", ")" ]
Marks a module level attribute as deprecated. Accessing it will emit a PyGIDeprecationWarning warning. e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")`` accessing GObject.STATUS_FOO will emit: "GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead" :param str namespace: The namespace of the override this is called in. :param str namespace: The attribute name (which gets added to __all__). :param str replacement: The replacement text which will be included in the warning.
[ "Marks", "a", "module", "level", "attribute", "as", "deprecated", ".", "Accessing", "it", "will", "emit", "a", "PyGIDeprecationWarning", "warning", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/__init__.py#L204-L221
train
pygobject/pgi
pgi/overrides/__init__.py
deprecated_init
def deprecated_init(super_init_func, arg_names, ignore=tuple(), deprecated_aliases={}, deprecated_defaults={}, category=PyGIDeprecationWarning, stacklevel=2): """Wrapper for deprecating GObject based __init__ methods which specify defaults already available or non-standard defaults. :param callable super_init_func: Initializer to wrap. :param list arg_names: Ordered argument name list. :param list ignore: List of argument names to ignore when calling the wrapped function. This is useful for function which take a non-standard keyword that is munged elsewhere. :param dict deprecated_aliases: Dictionary mapping a keyword alias to the actual g_object_newv keyword. :param dict deprecated_defaults: Dictionary of non-standard defaults that will be used when the keyword is not explicitly passed. :param Exception category: Exception category of the error. :param int stacklevel: Stack level for the deprecation passed on to warnings.warn :returns: Wrapped version of ``super_init_func`` which gives a deprecation warning when non-keyword args or aliases are used. :rtype: callable """ # We use a list of argument names to maintain order of the arguments # being deprecated. This allows calls with positional arguments to # continue working but with a deprecation message. def new_init(self, *args, **kwargs): """Initializer for a GObject based classes with support for property sets through the use of explicit keyword arguments. """ # Print warnings for calls with positional arguments. if args: warnings.warn('Using positional arguments with the GObject constructor has been deprecated. ' 'Please specify keyword(s) for "%s" or use a class specific constructor. ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' % ', '.join(arg_names[:len(args)]), category, stacklevel=stacklevel) new_kwargs = dict(zip(arg_names, args)) else: new_kwargs = {} new_kwargs.update(kwargs) # Print warnings for alias usage and transfer them into the new key. aliases_used = [] for key, alias in deprecated_aliases.items(): if alias in new_kwargs: new_kwargs[key] = new_kwargs.pop(alias) aliases_used.append(key) if aliases_used: warnings.warn('The keyword(s) "%s" have been deprecated in favor of "%s" respectively. ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' % (', '.join(deprecated_aliases[k] for k in sorted(aliases_used)), ', '.join(sorted(aliases_used))), category, stacklevel=stacklevel) # Print warnings for defaults different than what is already provided by the property defaults_used = [] for key, value in deprecated_defaults.items(): if key not in new_kwargs: new_kwargs[key] = deprecated_defaults[key] defaults_used.append(key) if defaults_used: warnings.warn('Initializer is relying on deprecated non-standard ' 'defaults. Please update to explicitly use: %s ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' % ', '.join('%s=%s' % (k, deprecated_defaults[k]) for k in sorted(defaults_used)), category, stacklevel=stacklevel) # Remove keywords that should be ignored. for key in ignore: if key in new_kwargs: new_kwargs.pop(key) return super_init_func(self, **new_kwargs) return new_init
python
def deprecated_init(super_init_func, arg_names, ignore=tuple(), deprecated_aliases={}, deprecated_defaults={}, category=PyGIDeprecationWarning, stacklevel=2): """Wrapper for deprecating GObject based __init__ methods which specify defaults already available or non-standard defaults. :param callable super_init_func: Initializer to wrap. :param list arg_names: Ordered argument name list. :param list ignore: List of argument names to ignore when calling the wrapped function. This is useful for function which take a non-standard keyword that is munged elsewhere. :param dict deprecated_aliases: Dictionary mapping a keyword alias to the actual g_object_newv keyword. :param dict deprecated_defaults: Dictionary of non-standard defaults that will be used when the keyword is not explicitly passed. :param Exception category: Exception category of the error. :param int stacklevel: Stack level for the deprecation passed on to warnings.warn :returns: Wrapped version of ``super_init_func`` which gives a deprecation warning when non-keyword args or aliases are used. :rtype: callable """ # We use a list of argument names to maintain order of the arguments # being deprecated. This allows calls with positional arguments to # continue working but with a deprecation message. def new_init(self, *args, **kwargs): """Initializer for a GObject based classes with support for property sets through the use of explicit keyword arguments. """ # Print warnings for calls with positional arguments. if args: warnings.warn('Using positional arguments with the GObject constructor has been deprecated. ' 'Please specify keyword(s) for "%s" or use a class specific constructor. ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' % ', '.join(arg_names[:len(args)]), category, stacklevel=stacklevel) new_kwargs = dict(zip(arg_names, args)) else: new_kwargs = {} new_kwargs.update(kwargs) # Print warnings for alias usage and transfer them into the new key. aliases_used = [] for key, alias in deprecated_aliases.items(): if alias in new_kwargs: new_kwargs[key] = new_kwargs.pop(alias) aliases_used.append(key) if aliases_used: warnings.warn('The keyword(s) "%s" have been deprecated in favor of "%s" respectively. ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' % (', '.join(deprecated_aliases[k] for k in sorted(aliases_used)), ', '.join(sorted(aliases_used))), category, stacklevel=stacklevel) # Print warnings for defaults different than what is already provided by the property defaults_used = [] for key, value in deprecated_defaults.items(): if key not in new_kwargs: new_kwargs[key] = deprecated_defaults[key] defaults_used.append(key) if defaults_used: warnings.warn('Initializer is relying on deprecated non-standard ' 'defaults. Please update to explicitly use: %s ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' % ', '.join('%s=%s' % (k, deprecated_defaults[k]) for k in sorted(defaults_used)), category, stacklevel=stacklevel) # Remove keywords that should be ignored. for key in ignore: if key in new_kwargs: new_kwargs.pop(key) return super_init_func(self, **new_kwargs) return new_init
[ "def", "deprecated_init", "(", "super_init_func", ",", "arg_names", ",", "ignore", "=", "tuple", "(", ")", ",", "deprecated_aliases", "=", "{", "}", ",", "deprecated_defaults", "=", "{", "}", ",", "category", "=", "PyGIDeprecationWarning", ",", "stacklevel", "=", "2", ")", ":", "# We use a list of argument names to maintain order of the arguments", "# being deprecated. This allows calls with positional arguments to", "# continue working but with a deprecation message.", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Initializer for a GObject based classes with support for property\n sets through the use of explicit keyword arguments.\n \"\"\"", "# Print warnings for calls with positional arguments.", "if", "args", ":", "warnings", ".", "warn", "(", "'Using positional arguments with the GObject constructor has been deprecated. '", "'Please specify keyword(s) for \"%s\" or use a class specific constructor. '", "'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations'", "%", "', '", ".", "join", "(", "arg_names", "[", ":", "len", "(", "args", ")", "]", ")", ",", "category", ",", "stacklevel", "=", "stacklevel", ")", "new_kwargs", "=", "dict", "(", "zip", "(", "arg_names", ",", "args", ")", ")", "else", ":", "new_kwargs", "=", "{", "}", "new_kwargs", ".", "update", "(", "kwargs", ")", "# Print warnings for alias usage and transfer them into the new key.", "aliases_used", "=", "[", "]", "for", "key", ",", "alias", "in", "deprecated_aliases", ".", "items", "(", ")", ":", "if", "alias", "in", "new_kwargs", ":", "new_kwargs", "[", "key", "]", "=", "new_kwargs", ".", "pop", "(", "alias", ")", "aliases_used", ".", "append", "(", "key", ")", "if", "aliases_used", ":", "warnings", ".", "warn", "(", "'The keyword(s) \"%s\" have been deprecated in favor of \"%s\" respectively. '", "'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations'", "%", "(", "', '", ".", "join", "(", "deprecated_aliases", "[", "k", "]", "for", "k", "in", "sorted", "(", "aliases_used", ")", ")", ",", "', '", ".", "join", "(", "sorted", "(", "aliases_used", ")", ")", ")", ",", "category", ",", "stacklevel", "=", "stacklevel", ")", "# Print warnings for defaults different than what is already provided by the property", "defaults_used", "=", "[", "]", "for", "key", ",", "value", "in", "deprecated_defaults", ".", "items", "(", ")", ":", "if", "key", "not", "in", "new_kwargs", ":", "new_kwargs", "[", "key", "]", "=", "deprecated_defaults", "[", "key", "]", "defaults_used", ".", "append", "(", "key", ")", "if", "defaults_used", ":", "warnings", ".", "warn", "(", "'Initializer is relying on deprecated non-standard '", "'defaults. Please update to explicitly use: %s '", "'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations'", "%", "', '", ".", "join", "(", "'%s=%s'", "%", "(", "k", ",", "deprecated_defaults", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "defaults_used", ")", ")", ",", "category", ",", "stacklevel", "=", "stacklevel", ")", "# Remove keywords that should be ignored.", "for", "key", "in", "ignore", ":", "if", "key", "in", "new_kwargs", ":", "new_kwargs", ".", "pop", "(", "key", ")", "return", "super_init_func", "(", "self", ",", "*", "*", "new_kwargs", ")", "return", "new_init" ]
Wrapper for deprecating GObject based __init__ methods which specify defaults already available or non-standard defaults. :param callable super_init_func: Initializer to wrap. :param list arg_names: Ordered argument name list. :param list ignore: List of argument names to ignore when calling the wrapped function. This is useful for function which take a non-standard keyword that is munged elsewhere. :param dict deprecated_aliases: Dictionary mapping a keyword alias to the actual g_object_newv keyword. :param dict deprecated_defaults: Dictionary of non-standard defaults that will be used when the keyword is not explicitly passed. :param Exception category: Exception category of the error. :param int stacklevel: Stack level for the deprecation passed on to warnings.warn :returns: Wrapped version of ``super_init_func`` which gives a deprecation warning when non-keyword args or aliases are used. :rtype: callable
[ "Wrapper", "for", "deprecating", "GObject", "based", "__init__", "methods", "which", "specify", "defaults", "already", "available", "or", "non", "-", "standard", "defaults", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/__init__.py#L224-L305
train
pygobject/pgi
pgi/overrides/__init__.py
strip_boolean_result
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None): """Translate method's return value for stripping off success flag. There are a lot of methods which return a "success" boolean and have several out arguments. Translate such a method to return the out arguments on success and None on failure. """ @wraps(method) def wrapped(*args, **kwargs): ret = method(*args, **kwargs) if ret[0]: if len(ret) == 2: return ret[1] else: return ret[1:] else: if exc_type: raise exc_type(exc_str or 'call failed') return fail_ret return wrapped
python
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None): """Translate method's return value for stripping off success flag. There are a lot of methods which return a "success" boolean and have several out arguments. Translate such a method to return the out arguments on success and None on failure. """ @wraps(method) def wrapped(*args, **kwargs): ret = method(*args, **kwargs) if ret[0]: if len(ret) == 2: return ret[1] else: return ret[1:] else: if exc_type: raise exc_type(exc_str or 'call failed') return fail_ret return wrapped
[ "def", "strip_boolean_result", "(", "method", ",", "exc_type", "=", "None", ",", "exc_str", "=", "None", ",", "fail_ret", "=", "None", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "ret", "[", "0", "]", ":", "if", "len", "(", "ret", ")", "==", "2", ":", "return", "ret", "[", "1", "]", "else", ":", "return", "ret", "[", "1", ":", "]", "else", ":", "if", "exc_type", ":", "raise", "exc_type", "(", "exc_str", "or", "'call failed'", ")", "return", "fail_ret", "return", "wrapped" ]
Translate method's return value for stripping off success flag. There are a lot of methods which return a "success" boolean and have several out arguments. Translate such a method to return the out arguments on success and None on failure.
[ "Translate", "method", "s", "return", "value", "for", "stripping", "off", "success", "flag", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/__init__.py#L308-L327
train
pygobject/pgi
pgi/module.py
get_introspection_module
def get_introspection_module(namespace): """Raises ImportError""" if namespace in _introspection_modules: return _introspection_modules[namespace] from . import get_required_version repository = GIRepository() version = get_required_version(namespace) try: repository.require(namespace, version, 0) except GIError as e: raise ImportError(e.message) # No strictly needed here, but most things will fail during use library = repository.get_shared_library(namespace) if library: library = library.split(",")[0] try: util.load_ctypes_library(library) except OSError: raise ImportError( "Couldn't load shared library %r" % library) # Generate bindings, set up lazy attributes instance = Module(repository, namespace) instance.__path__ = repository.get_typelib_path(namespace) instance.__package__ = const.PREFIX[0] instance.__file__ = "<%s.%s>" % (const.PREFIX[0], namespace) instance._version = version or repository.get_version(namespace) _introspection_modules[namespace] = instance return instance
python
def get_introspection_module(namespace): """Raises ImportError""" if namespace in _introspection_modules: return _introspection_modules[namespace] from . import get_required_version repository = GIRepository() version = get_required_version(namespace) try: repository.require(namespace, version, 0) except GIError as e: raise ImportError(e.message) # No strictly needed here, but most things will fail during use library = repository.get_shared_library(namespace) if library: library = library.split(",")[0] try: util.load_ctypes_library(library) except OSError: raise ImportError( "Couldn't load shared library %r" % library) # Generate bindings, set up lazy attributes instance = Module(repository, namespace) instance.__path__ = repository.get_typelib_path(namespace) instance.__package__ = const.PREFIX[0] instance.__file__ = "<%s.%s>" % (const.PREFIX[0], namespace) instance._version = version or repository.get_version(namespace) _introspection_modules[namespace] = instance return instance
[ "def", "get_introspection_module", "(", "namespace", ")", ":", "if", "namespace", "in", "_introspection_modules", ":", "return", "_introspection_modules", "[", "namespace", "]", "from", ".", "import", "get_required_version", "repository", "=", "GIRepository", "(", ")", "version", "=", "get_required_version", "(", "namespace", ")", "try", ":", "repository", ".", "require", "(", "namespace", ",", "version", ",", "0", ")", "except", "GIError", "as", "e", ":", "raise", "ImportError", "(", "e", ".", "message", ")", "# No strictly needed here, but most things will fail during use", "library", "=", "repository", ".", "get_shared_library", "(", "namespace", ")", "if", "library", ":", "library", "=", "library", ".", "split", "(", "\",\"", ")", "[", "0", "]", "try", ":", "util", ".", "load_ctypes_library", "(", "library", ")", "except", "OSError", ":", "raise", "ImportError", "(", "\"Couldn't load shared library %r\"", "%", "library", ")", "# Generate bindings, set up lazy attributes", "instance", "=", "Module", "(", "repository", ",", "namespace", ")", "instance", ".", "__path__", "=", "repository", ".", "get_typelib_path", "(", "namespace", ")", "instance", ".", "__package__", "=", "const", ".", "PREFIX", "[", "0", "]", "instance", ".", "__file__", "=", "\"<%s.%s>\"", "%", "(", "const", ".", "PREFIX", "[", "0", "]", ",", "namespace", ")", "instance", ".", "_version", "=", "version", "or", "repository", ".", "get_version", "(", "namespace", ")", "_introspection_modules", "[", "namespace", "]", "=", "instance", "return", "instance" ]
Raises ImportError
[ "Raises", "ImportError" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/module.py#L100-L135
train
pygobject/pgi
pgi/codegen/returnvalues.py
ReturnValue.get_param_type
def get_param_type(self, index): """Returns a ReturnValue instance for param type 'index'""" assert index in (0, 1) type_info = self.type.get_param_type(index) type_cls = get_return_class(type_info) instance = type_cls(None, type_info, [], self.backend) instance.setup() return instance
python
def get_param_type(self, index): """Returns a ReturnValue instance for param type 'index'""" assert index in (0, 1) type_info = self.type.get_param_type(index) type_cls = get_return_class(type_info) instance = type_cls(None, type_info, [], self.backend) instance.setup() return instance
[ "def", "get_param_type", "(", "self", ",", "index", ")", ":", "assert", "index", "in", "(", "0", ",", "1", ")", "type_info", "=", "self", ".", "type", ".", "get_param_type", "(", "index", ")", "type_cls", "=", "get_return_class", "(", "type_info", ")", "instance", "=", "type_cls", "(", "None", ",", "type_info", ",", "[", "]", ",", "self", ".", "backend", ")", "instance", ".", "setup", "(", ")", "return", "instance" ]
Returns a ReturnValue instance for param type 'index
[ "Returns", "a", "ReturnValue", "instance", "for", "param", "type", "index" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/returnvalues.py#L45-L54
train
pygobject/pgi
pgi/codegen/utils.py
parse_code
def parse_code(code, var_factory, **kwargs): """Parse a piece of text and substitude $var by either unique variable names or by the given kwargs mapping. Use $$ to escape $. Returns a CodeBlock and the resulting variable mapping. parse("$foo = $foo + $bar", bar="1") ("t1 = t1 + 1", {'foo': 't1', 'bar': '1'}) """ block = CodeBlock() defdict = collections.defaultdict(var_factory) defdict.update(kwargs) indent = -1 code = code.strip() for line in code.splitlines(): length = len(line) line = line.lstrip() spaces = length - len(line) if spaces: if indent < 0: indent = spaces level = 1 else: level = spaces // indent else: level = 0 # if there is a single variable and the to be inserted object # is a code block, insert the block with the current indentation level if line.startswith("$") and line.count("$") == 1: name = line[1:] if name in kwargs and isinstance(kwargs[name], CodeBlock): kwargs[name].write_into(block, level) continue block.write_line(string.Template(line).substitute(defdict), level) return block, dict(defdict)
python
def parse_code(code, var_factory, **kwargs): """Parse a piece of text and substitude $var by either unique variable names or by the given kwargs mapping. Use $$ to escape $. Returns a CodeBlock and the resulting variable mapping. parse("$foo = $foo + $bar", bar="1") ("t1 = t1 + 1", {'foo': 't1', 'bar': '1'}) """ block = CodeBlock() defdict = collections.defaultdict(var_factory) defdict.update(kwargs) indent = -1 code = code.strip() for line in code.splitlines(): length = len(line) line = line.lstrip() spaces = length - len(line) if spaces: if indent < 0: indent = spaces level = 1 else: level = spaces // indent else: level = 0 # if there is a single variable and the to be inserted object # is a code block, insert the block with the current indentation level if line.startswith("$") and line.count("$") == 1: name = line[1:] if name in kwargs and isinstance(kwargs[name], CodeBlock): kwargs[name].write_into(block, level) continue block.write_line(string.Template(line).substitute(defdict), level) return block, dict(defdict)
[ "def", "parse_code", "(", "code", ",", "var_factory", ",", "*", "*", "kwargs", ")", ":", "block", "=", "CodeBlock", "(", ")", "defdict", "=", "collections", ".", "defaultdict", "(", "var_factory", ")", "defdict", ".", "update", "(", "kwargs", ")", "indent", "=", "-", "1", "code", "=", "code", ".", "strip", "(", ")", "for", "line", "in", "code", ".", "splitlines", "(", ")", ":", "length", "=", "len", "(", "line", ")", "line", "=", "line", ".", "lstrip", "(", ")", "spaces", "=", "length", "-", "len", "(", "line", ")", "if", "spaces", ":", "if", "indent", "<", "0", ":", "indent", "=", "spaces", "level", "=", "1", "else", ":", "level", "=", "spaces", "//", "indent", "else", ":", "level", "=", "0", "# if there is a single variable and the to be inserted object", "# is a code block, insert the block with the current indentation level", "if", "line", ".", "startswith", "(", "\"$\"", ")", "and", "line", ".", "count", "(", "\"$\"", ")", "==", "1", ":", "name", "=", "line", "[", "1", ":", "]", "if", "name", "in", "kwargs", "and", "isinstance", "(", "kwargs", "[", "name", "]", ",", "CodeBlock", ")", ":", "kwargs", "[", "name", "]", ".", "write_into", "(", "block", ",", "level", ")", "continue", "block", ".", "write_line", "(", "string", ".", "Template", "(", "line", ")", ".", "substitute", "(", "defdict", ")", ",", "level", ")", "return", "block", ",", "dict", "(", "defdict", ")" ]
Parse a piece of text and substitude $var by either unique variable names or by the given kwargs mapping. Use $$ to escape $. Returns a CodeBlock and the resulting variable mapping. parse("$foo = $foo + $bar", bar="1") ("t1 = t1 + 1", {'foo': 't1', 'bar': '1'})
[ "Parse", "a", "piece", "of", "text", "and", "substitude", "$var", "by", "either", "unique", "variable", "names", "or", "by", "the", "given", "kwargs", "mapping", ".", "Use", "$$", "to", "escape", "$", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L179-L217
train
pygobject/pgi
pgi/codegen/utils.py
parse_with_objects
def parse_with_objects(code, var, **kwargs): """Parse code and include non string/codeblock kwargs as dependencies. int/long will be inlined. Returns a CodeBlock and the resulting variable mapping. """ deps = {} for key, value in kwargs.items(): if isinstance(value, _compat.integer_types): value = str(value) if _compat.PY3: if value is None: value = str(value) if not isinstance(value, _compat.string_types) and \ not isinstance(value, CodeBlock): new_var = var(value) deps[new_var] = value kwargs[key] = new_var block, var = parse_code(code, var, **kwargs) for key, dep in _compat.iteritems(deps): block.add_dependency(key, dep) return block, var
python
def parse_with_objects(code, var, **kwargs): """Parse code and include non string/codeblock kwargs as dependencies. int/long will be inlined. Returns a CodeBlock and the resulting variable mapping. """ deps = {} for key, value in kwargs.items(): if isinstance(value, _compat.integer_types): value = str(value) if _compat.PY3: if value is None: value = str(value) if not isinstance(value, _compat.string_types) and \ not isinstance(value, CodeBlock): new_var = var(value) deps[new_var] = value kwargs[key] = new_var block, var = parse_code(code, var, **kwargs) for key, dep in _compat.iteritems(deps): block.add_dependency(key, dep) return block, var
[ "def", "parse_with_objects", "(", "code", ",", "var", ",", "*", "*", "kwargs", ")", ":", "deps", "=", "{", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "_compat", ".", "integer_types", ")", ":", "value", "=", "str", "(", "value", ")", "if", "_compat", ".", "PY3", ":", "if", "value", "is", "None", ":", "value", "=", "str", "(", "value", ")", "if", "not", "isinstance", "(", "value", ",", "_compat", ".", "string_types", ")", "and", "not", "isinstance", "(", "value", ",", "CodeBlock", ")", ":", "new_var", "=", "var", "(", "value", ")", "deps", "[", "new_var", "]", "=", "value", "kwargs", "[", "key", "]", "=", "new_var", "block", ",", "var", "=", "parse_code", "(", "code", ",", "var", ",", "*", "*", "kwargs", ")", "for", "key", ",", "dep", "in", "_compat", ".", "iteritems", "(", "deps", ")", ":", "block", ".", "add_dependency", "(", "key", ",", "dep", ")", "return", "block", ",", "var" ]
Parse code and include non string/codeblock kwargs as dependencies. int/long will be inlined. Returns a CodeBlock and the resulting variable mapping.
[ "Parse", "code", "and", "include", "non", "string", "/", "codeblock", "kwargs", "as", "dependencies", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L220-L248
train
pygobject/pgi
pgi/codegen/utils.py
VariableFactory.request_name
def request_name(self, name): """Request a name, might return the name or a similar one if already used or reserved """ while name in self._blacklist: name += "_" self._blacklist.add(name) return name
python
def request_name(self, name): """Request a name, might return the name or a similar one if already used or reserved """ while name in self._blacklist: name += "_" self._blacklist.add(name) return name
[ "def", "request_name", "(", "self", ",", "name", ")", ":", "while", "name", "in", "self", ".", "_blacklist", ":", "name", "+=", "\"_\"", "self", ".", "_blacklist", ".", "add", "(", "name", ")", "return", "name" ]
Request a name, might return the name or a similar one if already used or reserved
[ "Request", "a", "name", "might", "return", "the", "name", "or", "a", "similar", "one", "if", "already", "used", "or", "reserved" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L68-L76
train
pygobject/pgi
pgi/codegen/utils.py
CodeBlock.add_dependency
def add_dependency(self, name, obj): """Add a code dependency so it gets inserted into globals""" if name in self._deps: if self._deps[name] is obj: return raise ValueError( "There exists a different dep with the same name : %r" % name) self._deps[name] = obj
python
def add_dependency(self, name, obj): """Add a code dependency so it gets inserted into globals""" if name in self._deps: if self._deps[name] is obj: return raise ValueError( "There exists a different dep with the same name : %r" % name) self._deps[name] = obj
[ "def", "add_dependency", "(", "self", ",", "name", ",", "obj", ")", ":", "if", "name", "in", "self", ".", "_deps", ":", "if", "self", ".", "_deps", "[", "name", "]", "is", "obj", ":", "return", "raise", "ValueError", "(", "\"There exists a different dep with the same name : %r\"", "%", "name", ")", "self", ".", "_deps", "[", "name", "]", "=", "obj" ]
Add a code dependency so it gets inserted into globals
[ "Add", "a", "code", "dependency", "so", "it", "gets", "inserted", "into", "globals" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L94-L102
train
pygobject/pgi
pgi/codegen/utils.py
CodeBlock.write_into
def write_into(self, block, level=0): """Append this block to another one, passing all dependencies""" for line, l in self._lines: block.write_line(line, level + l) for name, obj in _compat.iteritems(self._deps): block.add_dependency(name, obj)
python
def write_into(self, block, level=0): """Append this block to another one, passing all dependencies""" for line, l in self._lines: block.write_line(line, level + l) for name, obj in _compat.iteritems(self._deps): block.add_dependency(name, obj)
[ "def", "write_into", "(", "self", ",", "block", ",", "level", "=", "0", ")", ":", "for", "line", ",", "l", "in", "self", ".", "_lines", ":", "block", ".", "write_line", "(", "line", ",", "level", "+", "l", ")", "for", "name", ",", "obj", "in", "_compat", ".", "iteritems", "(", "self", ".", "_deps", ")", ":", "block", ".", "add_dependency", "(", "name", ",", "obj", ")" ]
Append this block to another one, passing all dependencies
[ "Append", "this", "block", "to", "another", "one", "passing", "all", "dependencies" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L104-L111
train
pygobject/pgi
pgi/codegen/utils.py
CodeBlock.write_lines
def write_lines(self, lines, level=0): """Append multiple new lines""" for line in lines: self.write_line(line, level)
python
def write_lines(self, lines, level=0): """Append multiple new lines""" for line in lines: self.write_line(line, level)
[ "def", "write_lines", "(", "self", ",", "lines", ",", "level", "=", "0", ")", ":", "for", "line", "in", "lines", ":", "self", ".", "write_line", "(", "line", ",", "level", ")" ]
Append multiple new lines
[ "Append", "multiple", "new", "lines" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L118-L122
train
pygobject/pgi
pgi/codegen/utils.py
CodeBlock.compile
def compile(self, **kwargs): """Execute the python code and returns the global dict. kwargs can contain extra dependencies that get only used at compile time. """ code = compile(str(self), "<string>", "exec") global_dict = dict(self._deps) global_dict.update(kwargs) _compat.exec_(code, global_dict) return global_dict
python
def compile(self, **kwargs): """Execute the python code and returns the global dict. kwargs can contain extra dependencies that get only used at compile time. """ code = compile(str(self), "<string>", "exec") global_dict = dict(self._deps) global_dict.update(kwargs) _compat.exec_(code, global_dict) return global_dict
[ "def", "compile", "(", "self", ",", "*", "*", "kwargs", ")", ":", "code", "=", "compile", "(", "str", "(", "self", ")", ",", "\"<string>\"", ",", "\"exec\"", ")", "global_dict", "=", "dict", "(", "self", ".", "_deps", ")", "global_dict", ".", "update", "(", "kwargs", ")", "_compat", ".", "exec_", "(", "code", ",", "global_dict", ")", "return", "global_dict" ]
Execute the python code and returns the global dict. kwargs can contain extra dependencies that get only used at compile time.
[ "Execute", "the", "python", "code", "and", "returns", "the", "global", "dict", ".", "kwargs", "can", "contain", "extra", "dependencies", "that", "get", "only", "used", "at", "compile", "time", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L124-L134
train
pygobject/pgi
pgi/codegen/utils.py
CodeBlock.pprint
def pprint(self, file_=sys.stdout): """Print the code block to stdout. Does syntax highlighting if possible. """ code = [] if self._deps: code.append("# dependencies:") for k, v in _compat.iteritems(self._deps): code.append("# %s: %r" % (k, v)) code.append(str(self)) code = "\n".join(code) if file_.isatty(): try: from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import TerminalFormatter except ImportError: pass else: formatter = TerminalFormatter(bg="dark") lexer = PythonLexer() file_.write(highlight(code, lexer, formatter)) return file_.write(code + "\n")
python
def pprint(self, file_=sys.stdout): """Print the code block to stdout. Does syntax highlighting if possible. """ code = [] if self._deps: code.append("# dependencies:") for k, v in _compat.iteritems(self._deps): code.append("# %s: %r" % (k, v)) code.append(str(self)) code = "\n".join(code) if file_.isatty(): try: from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import TerminalFormatter except ImportError: pass else: formatter = TerminalFormatter(bg="dark") lexer = PythonLexer() file_.write(highlight(code, lexer, formatter)) return file_.write(code + "\n")
[ "def", "pprint", "(", "self", ",", "file_", "=", "sys", ".", "stdout", ")", ":", "code", "=", "[", "]", "if", "self", ".", "_deps", ":", "code", ".", "append", "(", "\"# dependencies:\"", ")", "for", "k", ",", "v", "in", "_compat", ".", "iteritems", "(", "self", ".", "_deps", ")", ":", "code", ".", "append", "(", "\"# %s: %r\"", "%", "(", "k", ",", "v", ")", ")", "code", ".", "append", "(", "str", "(", "self", ")", ")", "code", "=", "\"\\n\"", ".", "join", "(", "code", ")", "if", "file_", ".", "isatty", "(", ")", ":", "try", ":", "from", "pygments", "import", "highlight", "from", "pygments", ".", "lexers", "import", "PythonLexer", "from", "pygments", ".", "formatters", "import", "TerminalFormatter", "except", "ImportError", ":", "pass", "else", ":", "formatter", "=", "TerminalFormatter", "(", "bg", "=", "\"dark\"", ")", "lexer", "=", "PythonLexer", "(", ")", "file_", ".", "write", "(", "highlight", "(", "code", ",", "lexer", ",", "formatter", ")", ")", "return", "file_", ".", "write", "(", "code", "+", "\"\\n\"", ")" ]
Print the code block to stdout. Does syntax highlighting if possible.
[ "Print", "the", "code", "block", "to", "stdout", ".", "Does", "syntax", "highlighting", "if", "possible", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L136-L161
train
pygobject/pgi
pgi/foreign/_base.py
ForeignStruct.register
def register(cls, namespace, name): """Class decorator""" def func(kind): cls._FOREIGN[(namespace, name)] = kind() return kind return func
python
def register(cls, namespace, name): """Class decorator""" def func(kind): cls._FOREIGN[(namespace, name)] = kind() return kind return func
[ "def", "register", "(", "cls", ",", "namespace", ",", "name", ")", ":", "def", "func", "(", "kind", ")", ":", "cls", ".", "_FOREIGN", "[", "(", "namespace", ",", "name", ")", "]", "=", "kind", "(", ")", "return", "kind", "return", "func" ]
Class decorator
[ "Class", "decorator" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/foreign/_base.py#L27-L33
train
pygobject/pgi
pgi/codegen/funcgen.py
may_be_null_is_nullable
def may_be_null_is_nullable(): """If may_be_null returns nullable or if NULL can be passed in. This can still be wrong if the specific typelib is older than the linked libgirepository. https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47 """ repo = GIRepository() repo.require("GLib", "2.0", 0) info = repo.find_by_name("GLib", "spawn_sync") # this argument is (allow-none) and can never be (nullable) return not info.get_arg(8).may_be_null
python
def may_be_null_is_nullable(): """If may_be_null returns nullable or if NULL can be passed in. This can still be wrong if the specific typelib is older than the linked libgirepository. https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47 """ repo = GIRepository() repo.require("GLib", "2.0", 0) info = repo.find_by_name("GLib", "spawn_sync") # this argument is (allow-none) and can never be (nullable) return not info.get_arg(8).may_be_null
[ "def", "may_be_null_is_nullable", "(", ")", ":", "repo", "=", "GIRepository", "(", ")", "repo", ".", "require", "(", "\"GLib\"", ",", "\"2.0\"", ",", "0", ")", "info", "=", "repo", ".", "find_by_name", "(", "\"GLib\"", ",", "\"spawn_sync\"", ")", "# this argument is (allow-none) and can never be (nullable)", "return", "not", "info", ".", "get_arg", "(", "8", ")", ".", "may_be_null" ]
If may_be_null returns nullable or if NULL can be passed in. This can still be wrong if the specific typelib is older than the linked libgirepository. https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47
[ "If", "may_be_null", "returns", "nullable", "or", "if", "NULL", "can", "be", "passed", "in", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/funcgen.py#L23-L36
train
pygobject/pgi
pgi/codegen/funcgen.py
get_type_name
def get_type_name(type_): """Gives a name for a type that is suitable for a docstring. int -> "int" Gtk.Window -> "Gtk.Window" [int] -> "[int]" {int: Gtk.Button} -> "{int: Gtk.Button}" """ if type_ is None: return "" if isinstance(type_, string_types): return type_ elif isinstance(type_, list): assert len(type_) == 1 return "[%s]" % get_type_name(type_[0]) elif isinstance(type_, dict): assert len(type_) == 1 key, value = list(type_.items())[0] return "{%s: %s}" % (get_type_name(key), get_type_name(value)) elif type_.__module__ in ("__builtin__", "builtins"): return type_.__name__ else: return "%s.%s" % (type_.__module__, type_.__name__)
python
def get_type_name(type_): """Gives a name for a type that is suitable for a docstring. int -> "int" Gtk.Window -> "Gtk.Window" [int] -> "[int]" {int: Gtk.Button} -> "{int: Gtk.Button}" """ if type_ is None: return "" if isinstance(type_, string_types): return type_ elif isinstance(type_, list): assert len(type_) == 1 return "[%s]" % get_type_name(type_[0]) elif isinstance(type_, dict): assert len(type_) == 1 key, value = list(type_.items())[0] return "{%s: %s}" % (get_type_name(key), get_type_name(value)) elif type_.__module__ in ("__builtin__", "builtins"): return type_.__name__ else: return "%s.%s" % (type_.__module__, type_.__name__)
[ "def", "get_type_name", "(", "type_", ")", ":", "if", "type_", "is", "None", ":", "return", "\"\"", "if", "isinstance", "(", "type_", ",", "string_types", ")", ":", "return", "type_", "elif", "isinstance", "(", "type_", ",", "list", ")", ":", "assert", "len", "(", "type_", ")", "==", "1", "return", "\"[%s]\"", "%", "get_type_name", "(", "type_", "[", "0", "]", ")", "elif", "isinstance", "(", "type_", ",", "dict", ")", ":", "assert", "len", "(", "type_", ")", "==", "1", "key", ",", "value", "=", "list", "(", "type_", ".", "items", "(", ")", ")", "[", "0", "]", "return", "\"{%s: %s}\"", "%", "(", "get_type_name", "(", "key", ")", ",", "get_type_name", "(", "value", ")", ")", "elif", "type_", ".", "__module__", "in", "(", "\"__builtin__\"", ",", "\"builtins\"", ")", ":", "return", "type_", ".", "__name__", "else", ":", "return", "\"%s.%s\"", "%", "(", "type_", ".", "__module__", ",", "type_", ".", "__name__", ")" ]
Gives a name for a type that is suitable for a docstring. int -> "int" Gtk.Window -> "Gtk.Window" [int] -> "[int]" {int: Gtk.Button} -> "{int: Gtk.Button}"
[ "Gives", "a", "name", "for", "a", "type", "that", "is", "suitable", "for", "a", "docstring", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/funcgen.py#L39-L62
train
pygobject/pgi
pgi/codegen/funcgen.py
build_docstring
def build_docstring(func_name, args, ret, throws, signal_owner_type=None): """Create a docstring in the form: name(in_name: type) -> (ret_type, out_name: type) """ out_args = [] if ret and not ret.ignore: if ret.py_type is None: out_args.append("unknown") else: tname = get_type_name(ret.py_type) if ret.may_return_null: tname += " or None" out_args.append(tname) in_args = [] if signal_owner_type is not None: name = get_signal_owner_var_name(signal_owner_type) in_args.append("%s: %s" % ( name, get_type_name(signal_owner_type.pytype))) for arg in args: if arg.is_aux: continue if arg.is_direction_in(): if arg.py_type is None: in_args.append(arg.in_var) else: tname = get_type_name(arg.py_type) if arg.may_be_null: tname += " or None" in_args.append("%s: %s" % (arg.in_var, tname)) if arg.is_direction_out(): if arg.py_type is None: out_args.append(arg.name) else: tname = get_type_name(arg.py_type) # if may_be_null means the arg is nullable, it is nullable # and the marshalling returns None for a NULL pointer if may_be_null_is_nullable() and arg.may_be_null and \ arg.can_unpack_none: tname += " or None" # When can we assume that out args return None? out_args.append("%s: %s" % (arg.name, tname)) in_def = ", ".join(in_args) if not out_args: out_def = "None" elif len(out_args) == 1: out_def = out_args[0] else: out_def = "(%s)" % ", ".join(out_args) error = "" if throws: error = "raises " return "%s(%s) %s-> %s" % (func_name, in_def, error, out_def)
python
def build_docstring(func_name, args, ret, throws, signal_owner_type=None): """Create a docstring in the form: name(in_name: type) -> (ret_type, out_name: type) """ out_args = [] if ret and not ret.ignore: if ret.py_type is None: out_args.append("unknown") else: tname = get_type_name(ret.py_type) if ret.may_return_null: tname += " or None" out_args.append(tname) in_args = [] if signal_owner_type is not None: name = get_signal_owner_var_name(signal_owner_type) in_args.append("%s: %s" % ( name, get_type_name(signal_owner_type.pytype))) for arg in args: if arg.is_aux: continue if arg.is_direction_in(): if arg.py_type is None: in_args.append(arg.in_var) else: tname = get_type_name(arg.py_type) if arg.may_be_null: tname += " or None" in_args.append("%s: %s" % (arg.in_var, tname)) if arg.is_direction_out(): if arg.py_type is None: out_args.append(arg.name) else: tname = get_type_name(arg.py_type) # if may_be_null means the arg is nullable, it is nullable # and the marshalling returns None for a NULL pointer if may_be_null_is_nullable() and arg.may_be_null and \ arg.can_unpack_none: tname += " or None" # When can we assume that out args return None? out_args.append("%s: %s" % (arg.name, tname)) in_def = ", ".join(in_args) if not out_args: out_def = "None" elif len(out_args) == 1: out_def = out_args[0] else: out_def = "(%s)" % ", ".join(out_args) error = "" if throws: error = "raises " return "%s(%s) %s-> %s" % (func_name, in_def, error, out_def)
[ "def", "build_docstring", "(", "func_name", ",", "args", ",", "ret", ",", "throws", ",", "signal_owner_type", "=", "None", ")", ":", "out_args", "=", "[", "]", "if", "ret", "and", "not", "ret", ".", "ignore", ":", "if", "ret", ".", "py_type", "is", "None", ":", "out_args", ".", "append", "(", "\"unknown\"", ")", "else", ":", "tname", "=", "get_type_name", "(", "ret", ".", "py_type", ")", "if", "ret", ".", "may_return_null", ":", "tname", "+=", "\" or None\"", "out_args", ".", "append", "(", "tname", ")", "in_args", "=", "[", "]", "if", "signal_owner_type", "is", "not", "None", ":", "name", "=", "get_signal_owner_var_name", "(", "signal_owner_type", ")", "in_args", ".", "append", "(", "\"%s: %s\"", "%", "(", "name", ",", "get_type_name", "(", "signal_owner_type", ".", "pytype", ")", ")", ")", "for", "arg", "in", "args", ":", "if", "arg", ".", "is_aux", ":", "continue", "if", "arg", ".", "is_direction_in", "(", ")", ":", "if", "arg", ".", "py_type", "is", "None", ":", "in_args", ".", "append", "(", "arg", ".", "in_var", ")", "else", ":", "tname", "=", "get_type_name", "(", "arg", ".", "py_type", ")", "if", "arg", ".", "may_be_null", ":", "tname", "+=", "\" or None\"", "in_args", ".", "append", "(", "\"%s: %s\"", "%", "(", "arg", ".", "in_var", ",", "tname", ")", ")", "if", "arg", ".", "is_direction_out", "(", ")", ":", "if", "arg", ".", "py_type", "is", "None", ":", "out_args", ".", "append", "(", "arg", ".", "name", ")", "else", ":", "tname", "=", "get_type_name", "(", "arg", ".", "py_type", ")", "# if may_be_null means the arg is nullable, it is nullable", "# and the marshalling returns None for a NULL pointer", "if", "may_be_null_is_nullable", "(", ")", "and", "arg", ".", "may_be_null", "and", "arg", ".", "can_unpack_none", ":", "tname", "+=", "\" or None\"", "# When can we assume that out args return None?", "out_args", ".", "append", "(", "\"%s: %s\"", "%", "(", "arg", ".", "name", ",", "tname", ")", ")", "in_def", "=", "\", \"", ".", "join", "(", "in_args", ")", "if", "not", "out_args", ":", "out_def", "=", "\"None\"", "elif", "len", "(", "out_args", ")", "==", "1", ":", "out_def", "=", "out_args", "[", "0", "]", "else", ":", "out_def", "=", "\"(%s)\"", "%", "\", \"", ".", "join", "(", "out_args", ")", "error", "=", "\"\"", "if", "throws", ":", "error", "=", "\"raises \"", "return", "\"%s(%s) %s-> %s\"", "%", "(", "func_name", ",", "in_def", ",", "error", ",", "out_def", ")" ]
Create a docstring in the form: name(in_name: type) -> (ret_type, out_name: type)
[ "Create", "a", "docstring", "in", "the", "form", ":", "name", "(", "in_name", ":", "type", ")", "-", ">", "(", "ret_type", "out_name", ":", "type", ")" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/funcgen.py#L71-L132
train
pygobject/pgi
pgi/codegen/funcgen.py
generate_function
def generate_function(info, method=False): """Creates a Python callable for a GIFunctionInfo instance""" assert isinstance(info, GIFunctionInfo) arg_infos = list(info.get_args()) arg_types = [a.get_type() for a in arg_infos] return_type = info.get_return_type() func = None messages = [] for backend in list_backends(): instance = backend() try: func = _generate_function(instance, info, arg_infos, arg_types, return_type, method) except NotImplementedError: messages.append("%s: %s" % (backend.NAME, traceback.format_exc())) else: break if func: return func raise NotImplementedError("\n".join(messages))
python
def generate_function(info, method=False): """Creates a Python callable for a GIFunctionInfo instance""" assert isinstance(info, GIFunctionInfo) arg_infos = list(info.get_args()) arg_types = [a.get_type() for a in arg_infos] return_type = info.get_return_type() func = None messages = [] for backend in list_backends(): instance = backend() try: func = _generate_function(instance, info, arg_infos, arg_types, return_type, method) except NotImplementedError: messages.append("%s: %s" % (backend.NAME, traceback.format_exc())) else: break if func: return func raise NotImplementedError("\n".join(messages))
[ "def", "generate_function", "(", "info", ",", "method", "=", "False", ")", ":", "assert", "isinstance", "(", "info", ",", "GIFunctionInfo", ")", "arg_infos", "=", "list", "(", "info", ".", "get_args", "(", ")", ")", "arg_types", "=", "[", "a", ".", "get_type", "(", ")", "for", "a", "in", "arg_infos", "]", "return_type", "=", "info", ".", "get_return_type", "(", ")", "func", "=", "None", "messages", "=", "[", "]", "for", "backend", "in", "list_backends", "(", ")", ":", "instance", "=", "backend", "(", ")", "try", ":", "func", "=", "_generate_function", "(", "instance", ",", "info", ",", "arg_infos", ",", "arg_types", ",", "return_type", ",", "method", ")", "except", "NotImplementedError", ":", "messages", ".", "append", "(", "\"%s: %s\"", "%", "(", "backend", ".", "NAME", ",", "traceback", ".", "format_exc", "(", ")", ")", ")", "else", ":", "break", "if", "func", ":", "return", "func", "raise", "NotImplementedError", "(", "\"\\n\"", ".", "join", "(", "messages", ")", ")" ]
Creates a Python callable for a GIFunctionInfo instance
[ "Creates", "a", "Python", "callable", "for", "a", "GIFunctionInfo", "instance" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/funcgen.py#L287-L311
train
pygobject/pgi
pgi/codegen/funcgen.py
generate_dummy_callable
def generate_dummy_callable(info, func_name, method=False, signal_owner_type=None): """Takes a GICallableInfo and generates a dummy callback function which just raises but has a correct docstring. They are mainly accessible for documentation, so the API reference can reference a real thing. func_name can be different than info.name because vfuncs, for example, get prefixed with 'do_' when exposed in Python. """ assert isinstance(info, GICallableInfo) # FIXME: handle out args and trailing user_data ? arg_infos = list(info.get_args()) arg_types = [a.get_type() for a in arg_infos] return_type = info.get_return_type() # the null backend is good enough here backend = get_backend("null")() args = [] for arg_info, arg_type in zip(arg_infos, arg_types): cls = get_argument_class(arg_type) name = escape_identifier(arg_info.name) name = escape_parameter(name) args.append(cls(name, args, backend, arg_info, arg_type)) cls = get_return_class(return_type) return_value = cls(info, return_type, args, backend) for arg in args: arg.setup() return_value.setup() in_args = [a for a in args if not a.is_aux and a.in_var] # if the last in argument is a closure, make it a var-positional argument if in_args and in_args[-1].closure != -1: name = in_args[-1].in_var in_args[-1].in_var = "*" + name func_name = escape_identifier(func_name) docstring = build_docstring(func_name, args, return_value, False, signal_owner_type) in_names = [a.in_var for a in in_args] var_fac = backend.var var_fac.add_blacklist(in_names) self_name = "" if method: self_name = var_fac.request_name("self") in_names.insert(0, self_name) main, var = backend.parse(""" def $func_name($func_args): '''$docstring''' raise NotImplementedError("This is just a dummy callback function") """, func_args=", ".join(in_names), docstring=docstring, func_name=func_name) func = main.compile()[func_name] func._code = main func.__doc__ = docstring func.__module__ = info.namespace return func
python
def generate_dummy_callable(info, func_name, method=False, signal_owner_type=None): """Takes a GICallableInfo and generates a dummy callback function which just raises but has a correct docstring. They are mainly accessible for documentation, so the API reference can reference a real thing. func_name can be different than info.name because vfuncs, for example, get prefixed with 'do_' when exposed in Python. """ assert isinstance(info, GICallableInfo) # FIXME: handle out args and trailing user_data ? arg_infos = list(info.get_args()) arg_types = [a.get_type() for a in arg_infos] return_type = info.get_return_type() # the null backend is good enough here backend = get_backend("null")() args = [] for arg_info, arg_type in zip(arg_infos, arg_types): cls = get_argument_class(arg_type) name = escape_identifier(arg_info.name) name = escape_parameter(name) args.append(cls(name, args, backend, arg_info, arg_type)) cls = get_return_class(return_type) return_value = cls(info, return_type, args, backend) for arg in args: arg.setup() return_value.setup() in_args = [a for a in args if not a.is_aux and a.in_var] # if the last in argument is a closure, make it a var-positional argument if in_args and in_args[-1].closure != -1: name = in_args[-1].in_var in_args[-1].in_var = "*" + name func_name = escape_identifier(func_name) docstring = build_docstring(func_name, args, return_value, False, signal_owner_type) in_names = [a.in_var for a in in_args] var_fac = backend.var var_fac.add_blacklist(in_names) self_name = "" if method: self_name = var_fac.request_name("self") in_names.insert(0, self_name) main, var = backend.parse(""" def $func_name($func_args): '''$docstring''' raise NotImplementedError("This is just a dummy callback function") """, func_args=", ".join(in_names), docstring=docstring, func_name=func_name) func = main.compile()[func_name] func._code = main func.__doc__ = docstring func.__module__ = info.namespace return func
[ "def", "generate_dummy_callable", "(", "info", ",", "func_name", ",", "method", "=", "False", ",", "signal_owner_type", "=", "None", ")", ":", "assert", "isinstance", "(", "info", ",", "GICallableInfo", ")", "# FIXME: handle out args and trailing user_data ?", "arg_infos", "=", "list", "(", "info", ".", "get_args", "(", ")", ")", "arg_types", "=", "[", "a", ".", "get_type", "(", ")", "for", "a", "in", "arg_infos", "]", "return_type", "=", "info", ".", "get_return_type", "(", ")", "# the null backend is good enough here", "backend", "=", "get_backend", "(", "\"null\"", ")", "(", ")", "args", "=", "[", "]", "for", "arg_info", ",", "arg_type", "in", "zip", "(", "arg_infos", ",", "arg_types", ")", ":", "cls", "=", "get_argument_class", "(", "arg_type", ")", "name", "=", "escape_identifier", "(", "arg_info", ".", "name", ")", "name", "=", "escape_parameter", "(", "name", ")", "args", ".", "append", "(", "cls", "(", "name", ",", "args", ",", "backend", ",", "arg_info", ",", "arg_type", ")", ")", "cls", "=", "get_return_class", "(", "return_type", ")", "return_value", "=", "cls", "(", "info", ",", "return_type", ",", "args", ",", "backend", ")", "for", "arg", "in", "args", ":", "arg", ".", "setup", "(", ")", "return_value", ".", "setup", "(", ")", "in_args", "=", "[", "a", "for", "a", "in", "args", "if", "not", "a", ".", "is_aux", "and", "a", ".", "in_var", "]", "# if the last in argument is a closure, make it a var-positional argument", "if", "in_args", "and", "in_args", "[", "-", "1", "]", ".", "closure", "!=", "-", "1", ":", "name", "=", "in_args", "[", "-", "1", "]", ".", "in_var", "in_args", "[", "-", "1", "]", ".", "in_var", "=", "\"*\"", "+", "name", "func_name", "=", "escape_identifier", "(", "func_name", ")", "docstring", "=", "build_docstring", "(", "func_name", ",", "args", ",", "return_value", ",", "False", ",", "signal_owner_type", ")", "in_names", "=", "[", "a", ".", "in_var", "for", "a", "in", "in_args", "]", "var_fac", "=", "backend", ".", "var", "var_fac", ".", "add_blacklist", "(", "in_names", ")", "self_name", "=", "\"\"", "if", "method", ":", "self_name", "=", "var_fac", ".", "request_name", "(", "\"self\"", ")", "in_names", ".", "insert", "(", "0", ",", "self_name", ")", "main", ",", "var", "=", "backend", ".", "parse", "(", "\"\"\"\ndef $func_name($func_args):\n '''$docstring'''\n\n raise NotImplementedError(\"This is just a dummy callback function\")\n\"\"\"", ",", "func_args", "=", "\", \"", ".", "join", "(", "in_names", ")", ",", "docstring", "=", "docstring", ",", "func_name", "=", "func_name", ")", "func", "=", "main", ".", "compile", "(", ")", "[", "func_name", "]", "func", ".", "_code", "=", "main", "func", ".", "__doc__", "=", "docstring", "func", ".", "__module__", "=", "info", ".", "namespace", "return", "func" ]
Takes a GICallableInfo and generates a dummy callback function which just raises but has a correct docstring. They are mainly accessible for documentation, so the API reference can reference a real thing. func_name can be different than info.name because vfuncs, for example, get prefixed with 'do_' when exposed in Python.
[ "Takes", "a", "GICallableInfo", "and", "generates", "a", "dummy", "callback", "function", "which", "just", "raises", "but", "has", "a", "correct", "docstring", ".", "They", "are", "mainly", "accessible", "for", "documentation", "so", "the", "API", "reference", "can", "reference", "a", "real", "thing", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/funcgen.py#L314-L382
train
pygobject/pgi
pgi/cffilib/_utils.py
_create_enum_class
def _create_enum_class(ffi, type_name, prefix, flags=False): """Returns a new shiny class for the given enum type""" class _template(int): _map = {} @property def value(self): return int(self) def __str__(self): return self._map.get(self, "Unknown") def __repr__(self): return "%s.%s" % (type(self).__name__, str(self)) class _template_flags(int): _map = {} @property def value(self): return int(self) def __str__(self): names = [] val = int(self) for flag, name in self._map.items(): if val & flag: names.append(name) val &= ~flag if val: names.append(str(val)) return " | ".join(sorted(names or ["Unknown"])) def __repr__(self): return "%s(%s)" % (type(self).__name__, str(self)) if flags: template = _template_flags else: template = _template cls = type(type_name, template.__bases__, dict(template.__dict__)) prefix_len = len(prefix) for value, name in ffi.typeof(type_name).elements.items(): assert name[:prefix_len] == prefix name = name[prefix_len:] setattr(cls, name, cls(value)) cls._map[value] = name return cls
python
def _create_enum_class(ffi, type_name, prefix, flags=False): """Returns a new shiny class for the given enum type""" class _template(int): _map = {} @property def value(self): return int(self) def __str__(self): return self._map.get(self, "Unknown") def __repr__(self): return "%s.%s" % (type(self).__name__, str(self)) class _template_flags(int): _map = {} @property def value(self): return int(self) def __str__(self): names = [] val = int(self) for flag, name in self._map.items(): if val & flag: names.append(name) val &= ~flag if val: names.append(str(val)) return " | ".join(sorted(names or ["Unknown"])) def __repr__(self): return "%s(%s)" % (type(self).__name__, str(self)) if flags: template = _template_flags else: template = _template cls = type(type_name, template.__bases__, dict(template.__dict__)) prefix_len = len(prefix) for value, name in ffi.typeof(type_name).elements.items(): assert name[:prefix_len] == prefix name = name[prefix_len:] setattr(cls, name, cls(value)) cls._map[value] = name return cls
[ "def", "_create_enum_class", "(", "ffi", ",", "type_name", ",", "prefix", ",", "flags", "=", "False", ")", ":", "class", "_template", "(", "int", ")", ":", "_map", "=", "{", "}", "@", "property", "def", "value", "(", "self", ")", ":", "return", "int", "(", "self", ")", "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "_map", ".", "get", "(", "self", ",", "\"Unknown\"", ")", "def", "__repr__", "(", "self", ")", ":", "return", "\"%s.%s\"", "%", "(", "type", "(", "self", ")", ".", "__name__", ",", "str", "(", "self", ")", ")", "class", "_template_flags", "(", "int", ")", ":", "_map", "=", "{", "}", "@", "property", "def", "value", "(", "self", ")", ":", "return", "int", "(", "self", ")", "def", "__str__", "(", "self", ")", ":", "names", "=", "[", "]", "val", "=", "int", "(", "self", ")", "for", "flag", ",", "name", "in", "self", ".", "_map", ".", "items", "(", ")", ":", "if", "val", "&", "flag", ":", "names", ".", "append", "(", "name", ")", "val", "&=", "~", "flag", "if", "val", ":", "names", ".", "append", "(", "str", "(", "val", ")", ")", "return", "\" | \"", ".", "join", "(", "sorted", "(", "names", "or", "[", "\"Unknown\"", "]", ")", ")", "def", "__repr__", "(", "self", ")", ":", "return", "\"%s(%s)\"", "%", "(", "type", "(", "self", ")", ".", "__name__", ",", "str", "(", "self", ")", ")", "if", "flags", ":", "template", "=", "_template_flags", "else", ":", "template", "=", "_template", "cls", "=", "type", "(", "type_name", ",", "template", ".", "__bases__", ",", "dict", "(", "template", ".", "__dict__", ")", ")", "prefix_len", "=", "len", "(", "prefix", ")", "for", "value", ",", "name", "in", "ffi", ".", "typeof", "(", "type_name", ")", ".", "elements", ".", "items", "(", ")", ":", "assert", "name", "[", ":", "prefix_len", "]", "==", "prefix", "name", "=", "name", "[", "prefix_len", ":", "]", "setattr", "(", "cls", ",", "name", ",", "cls", "(", "value", ")", ")", "cls", ".", "_map", "[", "value", "]", "=", "name", "return", "cls" ]
Returns a new shiny class for the given enum type
[ "Returns", "a", "new", "shiny", "class", "for", "the", "given", "enum", "type" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/cffilib/_utils.py#L58-L108
train
pygobject/pgi
pgi/cffilib/_utils.py
_fixup_cdef_enums
def _fixup_cdef_enums(string, reg=re.compile(r"=\s*(\d+)\s*<<\s*(\d+)")): """Converts some common enum expressions to constants""" def repl_shift(match): shift_by = int(match.group(2)) value = int(match.group(1)) int_value = ctypes.c_int(value << shift_by).value return "= %s" % str(int_value) return reg.sub(repl_shift, string)
python
def _fixup_cdef_enums(string, reg=re.compile(r"=\s*(\d+)\s*<<\s*(\d+)")): """Converts some common enum expressions to constants""" def repl_shift(match): shift_by = int(match.group(2)) value = int(match.group(1)) int_value = ctypes.c_int(value << shift_by).value return "= %s" % str(int_value) return reg.sub(repl_shift, string)
[ "def", "_fixup_cdef_enums", "(", "string", ",", "reg", "=", "re", ".", "compile", "(", "r\"=\\s*(\\d+)\\s*<<\\s*(\\d+)\"", ")", ")", ":", "def", "repl_shift", "(", "match", ")", ":", "shift_by", "=", "int", "(", "match", ".", "group", "(", "2", ")", ")", "value", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "int_value", "=", "ctypes", ".", "c_int", "(", "value", "<<", "shift_by", ")", ".", "value", "return", "\"= %s\"", "%", "str", "(", "int_value", ")", "return", "reg", ".", "sub", "(", "repl_shift", ",", "string", ")" ]
Converts some common enum expressions to constants
[ "Converts", "some", "common", "enum", "expressions", "to", "constants" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/cffilib/_utils.py#L111-L119
train
pygobject/pgi
pgi/clib/glib.py
unpack_glist
def unpack_glist(g, type_, transfer_full=True): """Takes a glist, copies the values casted to type_ in to a list and frees all items and the list. """ values = [] item = g while item: ptr = item.contents.data value = cast(ptr, type_).value values.append(value) if transfer_full: free(ptr) item = item.next() if transfer_full: g.free() return values
python
def unpack_glist(g, type_, transfer_full=True): """Takes a glist, copies the values casted to type_ in to a list and frees all items and the list. """ values = [] item = g while item: ptr = item.contents.data value = cast(ptr, type_).value values.append(value) if transfer_full: free(ptr) item = item.next() if transfer_full: g.free() return values
[ "def", "unpack_glist", "(", "g", ",", "type_", ",", "transfer_full", "=", "True", ")", ":", "values", "=", "[", "]", "item", "=", "g", "while", "item", ":", "ptr", "=", "item", ".", "contents", ".", "data", "value", "=", "cast", "(", "ptr", ",", "type_", ")", ".", "value", "values", ".", "append", "(", "value", ")", "if", "transfer_full", ":", "free", "(", "ptr", ")", "item", "=", "item", ".", "next", "(", ")", "if", "transfer_full", ":", "g", ".", "free", "(", ")", "return", "values" ]
Takes a glist, copies the values casted to type_ in to a list and frees all items and the list.
[ "Takes", "a", "glist", "copies", "the", "values", "casted", "to", "type_", "in", "to", "a", "list", "and", "frees", "all", "items", "and", "the", "list", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/glib.py#L281-L297
train
pygobject/pgi
pgi/clib/glib.py
unpack_nullterm_array
def unpack_nullterm_array(array): """Takes a null terminated array, copies the values into a list and frees each value and the list. """ addrs = cast(array, POINTER(ctypes.c_void_p)) l = [] i = 0 value = array[i] while value: l.append(value) free(addrs[i]) i += 1 value = array[i] free(addrs) return l
python
def unpack_nullterm_array(array): """Takes a null terminated array, copies the values into a list and frees each value and the list. """ addrs = cast(array, POINTER(ctypes.c_void_p)) l = [] i = 0 value = array[i] while value: l.append(value) free(addrs[i]) i += 1 value = array[i] free(addrs) return l
[ "def", "unpack_nullterm_array", "(", "array", ")", ":", "addrs", "=", "cast", "(", "array", ",", "POINTER", "(", "ctypes", ".", "c_void_p", ")", ")", "l", "=", "[", "]", "i", "=", "0", "value", "=", "array", "[", "i", "]", "while", "value", ":", "l", ".", "append", "(", "value", ")", "free", "(", "addrs", "[", "i", "]", ")", "i", "+=", "1", "value", "=", "array", "[", "i", "]", "free", "(", "addrs", ")", "return", "l" ]
Takes a null terminated array, copies the values into a list and frees each value and the list.
[ "Takes", "a", "null", "terminated", "array", "copies", "the", "values", "into", "a", "list", "and", "frees", "each", "value", "and", "the", "list", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/glib.py#L300-L315
train
pygobject/pgi
pgi/importer.py
require_version
def require_version(namespace, version): """Set a version for the namespace to be loaded. This needs to be called before importing the namespace or any namespace that depends on it. """ global _versions repo = GIRepository() namespaces = repo.get_loaded_namespaces() if namespace in namespaces: loaded_version = repo.get_version(namespace) if loaded_version != version: raise ValueError('Namespace %s is already loaded with version %s' % (namespace, loaded_version)) if namespace in _versions and _versions[namespace] != version: raise ValueError('Namespace %s already requires version %s' % (namespace, _versions[namespace])) available_versions = repo.enumerate_versions(namespace) if not available_versions: raise ValueError('Namespace %s not available' % namespace) if version not in available_versions: raise ValueError('Namespace %s not available for version %s' % (namespace, version)) _versions[namespace] = version
python
def require_version(namespace, version): """Set a version for the namespace to be loaded. This needs to be called before importing the namespace or any namespace that depends on it. """ global _versions repo = GIRepository() namespaces = repo.get_loaded_namespaces() if namespace in namespaces: loaded_version = repo.get_version(namespace) if loaded_version != version: raise ValueError('Namespace %s is already loaded with version %s' % (namespace, loaded_version)) if namespace in _versions and _versions[namespace] != version: raise ValueError('Namespace %s already requires version %s' % (namespace, _versions[namespace])) available_versions = repo.enumerate_versions(namespace) if not available_versions: raise ValueError('Namespace %s not available' % namespace) if version not in available_versions: raise ValueError('Namespace %s not available for version %s' % (namespace, version)) _versions[namespace] = version
[ "def", "require_version", "(", "namespace", ",", "version", ")", ":", "global", "_versions", "repo", "=", "GIRepository", "(", ")", "namespaces", "=", "repo", ".", "get_loaded_namespaces", "(", ")", "if", "namespace", "in", "namespaces", ":", "loaded_version", "=", "repo", ".", "get_version", "(", "namespace", ")", "if", "loaded_version", "!=", "version", ":", "raise", "ValueError", "(", "'Namespace %s is already loaded with version %s'", "%", "(", "namespace", ",", "loaded_version", ")", ")", "if", "namespace", "in", "_versions", "and", "_versions", "[", "namespace", "]", "!=", "version", ":", "raise", "ValueError", "(", "'Namespace %s already requires version %s'", "%", "(", "namespace", ",", "_versions", "[", "namespace", "]", ")", ")", "available_versions", "=", "repo", ".", "enumerate_versions", "(", "namespace", ")", "if", "not", "available_versions", ":", "raise", "ValueError", "(", "'Namespace %s not available'", "%", "namespace", ")", "if", "version", "not", "in", "available_versions", ":", "raise", "ValueError", "(", "'Namespace %s not available for version %s'", "%", "(", "namespace", ",", "version", ")", ")", "_versions", "[", "namespace", "]", "=", "version" ]
Set a version for the namespace to be loaded. This needs to be called before importing the namespace or any namespace that depends on it.
[ "Set", "a", "version", "for", "the", "namespace", "to", "be", "loaded", ".", "This", "needs", "to", "be", "called", "before", "importing", "the", "namespace", "or", "any", "namespace", "that", "depends", "on", "it", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/importer.py#L23-L52
train
pygobject/pgi
pgi/importer.py
_check_require_version
def _check_require_version(namespace, stacklevel): """A context manager which tries to give helpful warnings about missing gi.require_version() which could potentially break code if only an older version than expected is installed or a new version gets introduced. :: with _check_require_version("Gtk", stacklevel): load_namespace_and_overrides() """ repository = GIRepository() was_loaded = repository.is_registered(namespace) yield if was_loaded: # it was loaded before by another import which depended on this # namespace or by C code like libpeas return if namespace in ("GLib", "GObject", "Gio"): # part of glib (we have bigger problems if versions change there) return if get_required_version(namespace) is not None: # the version was forced using require_version() return version = repository.get_version(namespace) warnings.warn( "%(namespace)s was imported without specifying a version first. " "Use gi.require_version('%(namespace)s', '%(version)s') before " "import to ensure that the right version gets loaded." % {"namespace": namespace, "version": version}, PyGIWarning, stacklevel=stacklevel)
python
def _check_require_version(namespace, stacklevel): """A context manager which tries to give helpful warnings about missing gi.require_version() which could potentially break code if only an older version than expected is installed or a new version gets introduced. :: with _check_require_version("Gtk", stacklevel): load_namespace_and_overrides() """ repository = GIRepository() was_loaded = repository.is_registered(namespace) yield if was_loaded: # it was loaded before by another import which depended on this # namespace or by C code like libpeas return if namespace in ("GLib", "GObject", "Gio"): # part of glib (we have bigger problems if versions change there) return if get_required_version(namespace) is not None: # the version was forced using require_version() return version = repository.get_version(namespace) warnings.warn( "%(namespace)s was imported without specifying a version first. " "Use gi.require_version('%(namespace)s', '%(version)s') before " "import to ensure that the right version gets loaded." % {"namespace": namespace, "version": version}, PyGIWarning, stacklevel=stacklevel)
[ "def", "_check_require_version", "(", "namespace", ",", "stacklevel", ")", ":", "repository", "=", "GIRepository", "(", ")", "was_loaded", "=", "repository", ".", "is_registered", "(", "namespace", ")", "yield", "if", "was_loaded", ":", "# it was loaded before by another import which depended on this", "# namespace or by C code like libpeas", "return", "if", "namespace", "in", "(", "\"GLib\"", ",", "\"GObject\"", ",", "\"Gio\"", ")", ":", "# part of glib (we have bigger problems if versions change there)", "return", "if", "get_required_version", "(", "namespace", ")", "is", "not", "None", ":", "# the version was forced using require_version()", "return", "version", "=", "repository", ".", "get_version", "(", "namespace", ")", "warnings", ".", "warn", "(", "\"%(namespace)s was imported without specifying a version first. \"", "\"Use gi.require_version('%(namespace)s', '%(version)s') before \"", "\"import to ensure that the right version gets loaded.\"", "%", "{", "\"namespace\"", ":", "namespace", ",", "\"version\"", ":", "version", "}", ",", "PyGIWarning", ",", "stacklevel", "=", "stacklevel", ")" ]
A context manager which tries to give helpful warnings about missing gi.require_version() which could potentially break code if only an older version than expected is installed or a new version gets introduced. :: with _check_require_version("Gtk", stacklevel): load_namespace_and_overrides()
[ "A", "context", "manager", "which", "tries", "to", "give", "helpful", "warnings", "about", "missing", "gi", ".", "require_version", "()", "which", "could", "potentially", "break", "code", "if", "only", "an", "older", "version", "than", "expected", "is", "installed", "or", "a", "new", "version", "gets", "introduced", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/importer.py#L78-L114
train
pygobject/pgi
pgi/importer.py
get_import_stacklevel
def get_import_stacklevel(import_hook): """Returns the stacklevel value for warnings.warn() for when the warning gets emitted by an imported module, but the warning should point at the code doing the import. Pass import_hook=True if the warning gets generated by an import hook (warn() gets called in load_module(), see PEP302) """ py_version = sys.version_info[:2] if py_version <= (3, 2): # 2.7 included return 4 if import_hook else 2 elif py_version == (3, 3): return 8 if import_hook else 10 elif py_version == (3, 4): return 10 if import_hook else 8 else: # fixed again in 3.5+, see https://bugs.python.org/issue24305 return 4 if import_hook else 2
python
def get_import_stacklevel(import_hook): """Returns the stacklevel value for warnings.warn() for when the warning gets emitted by an imported module, but the warning should point at the code doing the import. Pass import_hook=True if the warning gets generated by an import hook (warn() gets called in load_module(), see PEP302) """ py_version = sys.version_info[:2] if py_version <= (3, 2): # 2.7 included return 4 if import_hook else 2 elif py_version == (3, 3): return 8 if import_hook else 10 elif py_version == (3, 4): return 10 if import_hook else 8 else: # fixed again in 3.5+, see https://bugs.python.org/issue24305 return 4 if import_hook else 2
[ "def", "get_import_stacklevel", "(", "import_hook", ")", ":", "py_version", "=", "sys", ".", "version_info", "[", ":", "2", "]", "if", "py_version", "<=", "(", "3", ",", "2", ")", ":", "# 2.7 included", "return", "4", "if", "import_hook", "else", "2", "elif", "py_version", "==", "(", "3", ",", "3", ")", ":", "return", "8", "if", "import_hook", "else", "10", "elif", "py_version", "==", "(", "3", ",", "4", ")", ":", "return", "10", "if", "import_hook", "else", "8", "else", ":", "# fixed again in 3.5+, see https://bugs.python.org/issue24305", "return", "4", "if", "import_hook", "else", "2" ]
Returns the stacklevel value for warnings.warn() for when the warning gets emitted by an imported module, but the warning should point at the code doing the import. Pass import_hook=True if the warning gets generated by an import hook (warn() gets called in load_module(), see PEP302)
[ "Returns", "the", "stacklevel", "value", "for", "warnings", ".", "warn", "()", "for", "when", "the", "warning", "gets", "emitted", "by", "an", "imported", "module", "but", "the", "warning", "should", "point", "at", "the", "code", "doing", "the", "import", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/importer.py#L117-L136
train
pygobject/pgi
pgi/cffilib/glib/glib.py
unpack_glist
def unpack_glist(glist_ptr, cffi_type, transfer_full=True): """Takes a glist ptr, copies the values casted to type_ in to a list and frees all items and the list. If an item is returned all yielded before are invalid. """ current = glist_ptr while current: yield ffi.cast(cffi_type, current.data) if transfer_full: free(current.data) current = current.next if transfer_full: lib.g_list_free(glist_ptr)
python
def unpack_glist(glist_ptr, cffi_type, transfer_full=True): """Takes a glist ptr, copies the values casted to type_ in to a list and frees all items and the list. If an item is returned all yielded before are invalid. """ current = glist_ptr while current: yield ffi.cast(cffi_type, current.data) if transfer_full: free(current.data) current = current.next if transfer_full: lib.g_list_free(glist_ptr)
[ "def", "unpack_glist", "(", "glist_ptr", ",", "cffi_type", ",", "transfer_full", "=", "True", ")", ":", "current", "=", "glist_ptr", "while", "current", ":", "yield", "ffi", ".", "cast", "(", "cffi_type", ",", "current", ".", "data", ")", "if", "transfer_full", ":", "free", "(", "current", ".", "data", ")", "current", "=", "current", ".", "next", "if", "transfer_full", ":", "lib", ".", "g_list_free", "(", "glist_ptr", ")" ]
Takes a glist ptr, copies the values casted to type_ in to a list and frees all items and the list. If an item is returned all yielded before are invalid.
[ "Takes", "a", "glist", "ptr", "copies", "the", "values", "casted", "to", "type_", "in", "to", "a", "list", "and", "frees", "all", "items", "and", "the", "list", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/cffilib/glib/glib.py#L227-L241
train
pygobject/pgi
pgi/cffilib/glib/glib.py
unpack_zeroterm_array
def unpack_zeroterm_array(ptr): """Converts a zero terminated array to a list and frees each element and the list itself. If an item is returned all yielded before are invalid. """ assert ptr index = 0 current = ptr[index] while current: yield current free(ffi.cast("gpointer", current)) index += 1 current = ptr[index] free(ffi.cast("gpointer", ptr))
python
def unpack_zeroterm_array(ptr): """Converts a zero terminated array to a list and frees each element and the list itself. If an item is returned all yielded before are invalid. """ assert ptr index = 0 current = ptr[index] while current: yield current free(ffi.cast("gpointer", current)) index += 1 current = ptr[index] free(ffi.cast("gpointer", ptr))
[ "def", "unpack_zeroterm_array", "(", "ptr", ")", ":", "assert", "ptr", "index", "=", "0", "current", "=", "ptr", "[", "index", "]", "while", "current", ":", "yield", "current", "free", "(", "ffi", ".", "cast", "(", "\"gpointer\"", ",", "current", ")", ")", "index", "+=", "1", "current", "=", "ptr", "[", "index", "]", "free", "(", "ffi", ".", "cast", "(", "\"gpointer\"", ",", "ptr", ")", ")" ]
Converts a zero terminated array to a list and frees each element and the list itself. If an item is returned all yielded before are invalid.
[ "Converts", "a", "zero", "terminated", "array", "to", "a", "list", "and", "frees", "each", "element", "and", "the", "list", "itself", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/cffilib/glib/glib.py#L244-L260
train
pygobject/pgi
pgi/structure.py
StructureAttribute
def StructureAttribute(struct_info): """Creates a new struct class.""" # Copy the template and add the gtype cls_dict = dict(_Structure.__dict__) cls = type(struct_info.name, _Structure.__bases__, cls_dict) cls.__module__ = struct_info.namespace cls.__gtype__ = PGType(struct_info.g_type) cls._size = struct_info.size cls._is_gtype_struct = struct_info.is_gtype_struct # Add methods for method_info in struct_info.get_methods(): add_method(method_info, cls) # Add fields for field_info in struct_info.get_fields(): field_name = escape_identifier(field_info.name) attr = FieldAttribute(field_name, field_info) setattr(cls, field_name, attr) return cls
python
def StructureAttribute(struct_info): """Creates a new struct class.""" # Copy the template and add the gtype cls_dict = dict(_Structure.__dict__) cls = type(struct_info.name, _Structure.__bases__, cls_dict) cls.__module__ = struct_info.namespace cls.__gtype__ = PGType(struct_info.g_type) cls._size = struct_info.size cls._is_gtype_struct = struct_info.is_gtype_struct # Add methods for method_info in struct_info.get_methods(): add_method(method_info, cls) # Add fields for field_info in struct_info.get_fields(): field_name = escape_identifier(field_info.name) attr = FieldAttribute(field_name, field_info) setattr(cls, field_name, attr) return cls
[ "def", "StructureAttribute", "(", "struct_info", ")", ":", "# Copy the template and add the gtype", "cls_dict", "=", "dict", "(", "_Structure", ".", "__dict__", ")", "cls", "=", "type", "(", "struct_info", ".", "name", ",", "_Structure", ".", "__bases__", ",", "cls_dict", ")", "cls", ".", "__module__", "=", "struct_info", ".", "namespace", "cls", ".", "__gtype__", "=", "PGType", "(", "struct_info", ".", "g_type", ")", "cls", ".", "_size", "=", "struct_info", ".", "size", "cls", ".", "_is_gtype_struct", "=", "struct_info", ".", "is_gtype_struct", "# Add methods", "for", "method_info", "in", "struct_info", ".", "get_methods", "(", ")", ":", "add_method", "(", "method_info", ",", "cls", ")", "# Add fields", "for", "field_info", "in", "struct_info", ".", "get_fields", "(", ")", ":", "field_name", "=", "escape_identifier", "(", "field_info", ".", "name", ")", "attr", "=", "FieldAttribute", "(", "field_name", ",", "field_info", ")", "setattr", "(", "cls", ",", "field_name", ",", "attr", ")", "return", "cls" ]
Creates a new struct class.
[ "Creates", "a", "new", "struct", "class", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/structure.py#L110-L131
train
pygobject/pgi
pgi/gerror.py
PGError._from_gerror
def _from_gerror(cls, error, own=True): """Creates a GError exception and takes ownership if own is True""" if not own: error = error.copy() self = cls() self._error = error return self
python
def _from_gerror(cls, error, own=True): """Creates a GError exception and takes ownership if own is True""" if not own: error = error.copy() self = cls() self._error = error return self
[ "def", "_from_gerror", "(", "cls", ",", "error", ",", "own", "=", "True", ")", ":", "if", "not", "own", ":", "error", "=", "error", ".", "copy", "(", ")", "self", "=", "cls", "(", ")", "self", ".", "_error", "=", "error", "return", "self" ]
Creates a GError exception and takes ownership if own is True
[ "Creates", "a", "GError", "exception", "and", "takes", "ownership", "if", "own", "is", "True" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/gerror.py#L17-L25
train
pygobject/pgi
pgi/__init__.py
check_version
def check_version(version): """Takes a version string or tuple and raises ValueError in case the passed version is newer than the current version of pgi. Keep in mind that the pgi version is different from the pygobject one. """ if isinstance(version, string_types): version = tuple(map(int, version.split("."))) if version > version_info: str_version = ".".join(map(str, version)) raise ValueError("pgi version '%s' requested, '%s' available" % (str_version, __version__))
python
def check_version(version): """Takes a version string or tuple and raises ValueError in case the passed version is newer than the current version of pgi. Keep in mind that the pgi version is different from the pygobject one. """ if isinstance(version, string_types): version = tuple(map(int, version.split("."))) if version > version_info: str_version = ".".join(map(str, version)) raise ValueError("pgi version '%s' requested, '%s' available" % (str_version, __version__))
[ "def", "check_version", "(", "version", ")", ":", "if", "isinstance", "(", "version", ",", "string_types", ")", ":", "version", "=", "tuple", "(", "map", "(", "int", ",", "version", ".", "split", "(", "\".\"", ")", ")", ")", "if", "version", ">", "version_info", ":", "str_version", "=", "\".\"", ".", "join", "(", "map", "(", "str", ",", "version", ")", ")", "raise", "ValueError", "(", "\"pgi version '%s' requested, '%s' available\"", "%", "(", "str_version", ",", "__version__", ")", ")" ]
Takes a version string or tuple and raises ValueError in case the passed version is newer than the current version of pgi. Keep in mind that the pgi version is different from the pygobject one.
[ "Takes", "a", "version", "string", "or", "tuple", "and", "raises", "ValueError", "in", "case", "the", "passed", "version", "is", "newer", "than", "the", "current", "version", "of", "pgi", "." ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/__init__.py#L27-L40
train
pygobject/pgi
pgi/__init__.py
install_as_gi
def install_as_gi(): """Call before the first gi import to redirect gi imports to pgi""" import sys # check if gi has already been replaces if "gi.repository" in const.PREFIX: return # make sure gi isn't loaded first for mod in iterkeys(sys.modules): if mod == "gi" or mod.startswith("gi."): raise AssertionError("pgi has to be imported before gi") # replace and tell the import hook import pgi import pgi.repository sys.modules["gi"] = pgi sys.modules["gi.repository"] = pgi.repository const.PREFIX.append("gi.repository")
python
def install_as_gi(): """Call before the first gi import to redirect gi imports to pgi""" import sys # check if gi has already been replaces if "gi.repository" in const.PREFIX: return # make sure gi isn't loaded first for mod in iterkeys(sys.modules): if mod == "gi" or mod.startswith("gi."): raise AssertionError("pgi has to be imported before gi") # replace and tell the import hook import pgi import pgi.repository sys.modules["gi"] = pgi sys.modules["gi.repository"] = pgi.repository const.PREFIX.append("gi.repository")
[ "def", "install_as_gi", "(", ")", ":", "import", "sys", "# check if gi has already been replaces", "if", "\"gi.repository\"", "in", "const", ".", "PREFIX", ":", "return", "# make sure gi isn't loaded first", "for", "mod", "in", "iterkeys", "(", "sys", ".", "modules", ")", ":", "if", "mod", "==", "\"gi\"", "or", "mod", ".", "startswith", "(", "\"gi.\"", ")", ":", "raise", "AssertionError", "(", "\"pgi has to be imported before gi\"", ")", "# replace and tell the import hook", "import", "pgi", "import", "pgi", ".", "repository", "sys", ".", "modules", "[", "\"gi\"", "]", "=", "pgi", "sys", ".", "modules", "[", "\"gi.repository\"", "]", "=", "pgi", ".", "repository", "const", ".", "PREFIX", ".", "append", "(", "\"gi.repository\"", ")" ]
Call before the first gi import to redirect gi imports to pgi
[ "Call", "before", "the", "first", "gi", "import", "to", "redirect", "gi", "imports", "to", "pgi" ]
2090435df6241a15ec2a78379a36b738b728652c
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/__init__.py#L43-L62
train
rfosterslo/wagtailplus
wagtailplus/utils/edit_handlers.py
add_panel_to_edit_handler
def add_panel_to_edit_handler(model, panel_cls, heading, index=None): """ Adds specified panel class to model class. :param model: the model class. :param panel_cls: the panel class. :param heading: the panel heading. :param index: the index position to insert at. """ from wagtail.wagtailadmin.views.pages import get_page_edit_handler edit_handler = get_page_edit_handler(model) panel_instance = ObjectList( [panel_cls(),], heading = heading ).bind_to_model(model) if index: edit_handler.children.insert(index, panel_instance) else: edit_handler.children.append(panel_instance)
python
def add_panel_to_edit_handler(model, panel_cls, heading, index=None): """ Adds specified panel class to model class. :param model: the model class. :param panel_cls: the panel class. :param heading: the panel heading. :param index: the index position to insert at. """ from wagtail.wagtailadmin.views.pages import get_page_edit_handler edit_handler = get_page_edit_handler(model) panel_instance = ObjectList( [panel_cls(),], heading = heading ).bind_to_model(model) if index: edit_handler.children.insert(index, panel_instance) else: edit_handler.children.append(panel_instance)
[ "def", "add_panel_to_edit_handler", "(", "model", ",", "panel_cls", ",", "heading", ",", "index", "=", "None", ")", ":", "from", "wagtail", ".", "wagtailadmin", ".", "views", ".", "pages", "import", "get_page_edit_handler", "edit_handler", "=", "get_page_edit_handler", "(", "model", ")", "panel_instance", "=", "ObjectList", "(", "[", "panel_cls", "(", ")", ",", "]", ",", "heading", "=", "heading", ")", ".", "bind_to_model", "(", "model", ")", "if", "index", ":", "edit_handler", ".", "children", ".", "insert", "(", "index", ",", "panel_instance", ")", "else", ":", "edit_handler", ".", "children", ".", "append", "(", "panel_instance", ")" ]
Adds specified panel class to model class. :param model: the model class. :param panel_cls: the panel class. :param heading: the panel heading. :param index: the index position to insert at.
[ "Adds", "specified", "panel", "class", "to", "model", "class", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/edit_handlers.py#L7-L27
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
IndexView.get_context_data
def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ #noinspection PyUnresolvedReferences query_str = self.request.GET.get('q', None) queryset = kwargs.pop('object_list', self.object_list) context_object_name = self.get_context_object_name(queryset) # Build the context dictionary. context = { 'ordering': self.get_ordering(), 'query_string': query_str, 'is_searching': bool(query_str), } # Add extra variables to context for non-AJAX requests. #noinspection PyUnresolvedReferences if not self.request.is_ajax() or kwargs.get('force_search', False): context.update({ 'search_form': self.get_search_form(), 'popular_tags': self.model.popular_tags() }) if context_object_name is not None: context[context_object_name] = queryset # Update context with any additional keyword arguments. context.update(kwargs) return super(IndexView, self).get_context_data(**context)
python
def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ #noinspection PyUnresolvedReferences query_str = self.request.GET.get('q', None) queryset = kwargs.pop('object_list', self.object_list) context_object_name = self.get_context_object_name(queryset) # Build the context dictionary. context = { 'ordering': self.get_ordering(), 'query_string': query_str, 'is_searching': bool(query_str), } # Add extra variables to context for non-AJAX requests. #noinspection PyUnresolvedReferences if not self.request.is_ajax() or kwargs.get('force_search', False): context.update({ 'search_form': self.get_search_form(), 'popular_tags': self.model.popular_tags() }) if context_object_name is not None: context[context_object_name] = queryset # Update context with any additional keyword arguments. context.update(kwargs) return super(IndexView, self).get_context_data(**context)
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "#noinspection PyUnresolvedReferences", "query_str", "=", "self", ".", "request", ".", "GET", ".", "get", "(", "'q'", ",", "None", ")", "queryset", "=", "kwargs", ".", "pop", "(", "'object_list'", ",", "self", ".", "object_list", ")", "context_object_name", "=", "self", ".", "get_context_object_name", "(", "queryset", ")", "# Build the context dictionary.", "context", "=", "{", "'ordering'", ":", "self", ".", "get_ordering", "(", ")", ",", "'query_string'", ":", "query_str", ",", "'is_searching'", ":", "bool", "(", "query_str", ")", ",", "}", "# Add extra variables to context for non-AJAX requests.", "#noinspection PyUnresolvedReferences", "if", "not", "self", ".", "request", ".", "is_ajax", "(", ")", "or", "kwargs", ".", "get", "(", "'force_search'", ",", "False", ")", ":", "context", ".", "update", "(", "{", "'search_form'", ":", "self", ".", "get_search_form", "(", ")", ",", "'popular_tags'", ":", "self", ".", "model", ".", "popular_tags", "(", ")", "}", ")", "if", "context_object_name", "is", "not", "None", ":", "context", "[", "context_object_name", "]", "=", "queryset", "# Update context with any additional keyword arguments.", "context", ".", "update", "(", "kwargs", ")", "return", "super", "(", "IndexView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "context", ")" ]
Returns context dictionary for view. :rtype: dict.
[ "Returns", "context", "dictionary", "for", "view", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L51-L83
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
IndexView.get_ordering
def get_ordering(self): """ Returns ordering value for list. :rtype: str. """ #noinspection PyUnresolvedReferences ordering = self.request.GET.get('ordering', None) if ordering not in ['title', '-created_at']: ordering = '-created_at' return ordering
python
def get_ordering(self): """ Returns ordering value for list. :rtype: str. """ #noinspection PyUnresolvedReferences ordering = self.request.GET.get('ordering', None) if ordering not in ['title', '-created_at']: ordering = '-created_at' return ordering
[ "def", "get_ordering", "(", "self", ")", ":", "#noinspection PyUnresolvedReferences", "ordering", "=", "self", ".", "request", ".", "GET", ".", "get", "(", "'ordering'", ",", "None", ")", "if", "ordering", "not", "in", "[", "'title'", ",", "'-created_at'", "]", ":", "ordering", "=", "'-created_at'", "return", "ordering" ]
Returns ordering value for list. :rtype: str.
[ "Returns", "ordering", "value", "for", "list", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L85-L97
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
IndexView.get_queryset
def get_queryset(self): """ Returns queryset instance. :rtype: django.db.models.query.QuerySet. """ queryset = super(IndexView, self).get_queryset() search_form = self.get_search_form() if search_form.is_valid(): query_str = search_form.cleaned_data.get('q', '').strip() queryset = self.model.objects.search(query_str) return queryset
python
def get_queryset(self): """ Returns queryset instance. :rtype: django.db.models.query.QuerySet. """ queryset = super(IndexView, self).get_queryset() search_form = self.get_search_form() if search_form.is_valid(): query_str = search_form.cleaned_data.get('q', '').strip() queryset = self.model.objects.search(query_str) return queryset
[ "def", "get_queryset", "(", "self", ")", ":", "queryset", "=", "super", "(", "IndexView", ",", "self", ")", ".", "get_queryset", "(", ")", "search_form", "=", "self", ".", "get_search_form", "(", ")", "if", "search_form", ".", "is_valid", "(", ")", ":", "query_str", "=", "search_form", ".", "cleaned_data", ".", "get", "(", "'q'", ",", "''", ")", ".", "strip", "(", ")", "queryset", "=", "self", ".", "model", ".", "objects", ".", "search", "(", "query_str", ")", "return", "queryset" ]
Returns queryset instance. :rtype: django.db.models.query.QuerySet.
[ "Returns", "queryset", "instance", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L99-L112
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
IndexView.get_search_form
def get_search_form(self): """ Returns search form instance. :rtype: django.forms.ModelForm. """ #noinspection PyUnresolvedReferences if 'q' in self.request.GET: #noinspection PyUnresolvedReferences return self.search_form_class(self.request.GET) else: return self.search_form_class(placeholder=_(u'Search'))
python
def get_search_form(self): """ Returns search form instance. :rtype: django.forms.ModelForm. """ #noinspection PyUnresolvedReferences if 'q' in self.request.GET: #noinspection PyUnresolvedReferences return self.search_form_class(self.request.GET) else: return self.search_form_class(placeholder=_(u'Search'))
[ "def", "get_search_form", "(", "self", ")", ":", "#noinspection PyUnresolvedReferences", "if", "'q'", "in", "self", ".", "request", ".", "GET", ":", "#noinspection PyUnresolvedReferences", "return", "self", ".", "search_form_class", "(", "self", ".", "request", ".", "GET", ")", "else", ":", "return", "self", ".", "search_form_class", "(", "placeholder", "=", "_", "(", "u'Search'", ")", ")" ]
Returns search form instance. :rtype: django.forms.ModelForm.
[ "Returns", "search", "form", "instance", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L114-L125
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
IndexView.get_template_names
def get_template_names(self): """ Returns a list of template names for the view. :rtype: list. """ #noinspection PyUnresolvedReferences if self.request.is_ajax(): template_name = '/results.html' else: template_name = '/index.html' return ['{0}{1}'.format(self.template_dir, template_name)]
python
def get_template_names(self): """ Returns a list of template names for the view. :rtype: list. """ #noinspection PyUnresolvedReferences if self.request.is_ajax(): template_name = '/results.html' else: template_name = '/index.html' return ['{0}{1}'.format(self.template_dir, template_name)]
[ "def", "get_template_names", "(", "self", ")", ":", "#noinspection PyUnresolvedReferences", "if", "self", ".", "request", ".", "is_ajax", "(", ")", ":", "template_name", "=", "'/results.html'", "else", ":", "template_name", "=", "'/index.html'", "return", "[", "'{0}{1}'", ".", "format", "(", "self", ".", "template_dir", ",", "template_name", ")", "]" ]
Returns a list of template names for the view. :rtype: list.
[ "Returns", "a", "list", "of", "template", "names", "for", "the", "view", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L127-L139
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
IndexView.paginate_queryset
def paginate_queryset(self, queryset, page_size): """ Returns tuple containing paginator instance, page instance, object list, and whether there are other pages. :param queryset: the queryset instance to paginate. :param page_size: the number of instances per page. :rtype: tuple. """ paginator = self.get_paginator( queryset, page_size, orphans = self.get_paginate_orphans(), allow_empty_first_page = self.get_allow_empty() ) page_kwarg = self.page_kwarg #noinspection PyUnresolvedReferences page_num = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 # Default to a valid page. try: page = paginator.page(page_num) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) #noinspection PyRedundantParentheses return (paginator, page, page.object_list, page.has_other_pages())
python
def paginate_queryset(self, queryset, page_size): """ Returns tuple containing paginator instance, page instance, object list, and whether there are other pages. :param queryset: the queryset instance to paginate. :param page_size: the number of instances per page. :rtype: tuple. """ paginator = self.get_paginator( queryset, page_size, orphans = self.get_paginate_orphans(), allow_empty_first_page = self.get_allow_empty() ) page_kwarg = self.page_kwarg #noinspection PyUnresolvedReferences page_num = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 # Default to a valid page. try: page = paginator.page(page_num) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) #noinspection PyRedundantParentheses return (paginator, page, page.object_list, page.has_other_pages())
[ "def", "paginate_queryset", "(", "self", ",", "queryset", ",", "page_size", ")", ":", "paginator", "=", "self", ".", "get_paginator", "(", "queryset", ",", "page_size", ",", "orphans", "=", "self", ".", "get_paginate_orphans", "(", ")", ",", "allow_empty_first_page", "=", "self", ".", "get_allow_empty", "(", ")", ")", "page_kwarg", "=", "self", ".", "page_kwarg", "#noinspection PyUnresolvedReferences", "page_num", "=", "self", ".", "kwargs", ".", "get", "(", "page_kwarg", ")", "or", "self", ".", "request", ".", "GET", ".", "get", "(", "page_kwarg", ")", "or", "1", "# Default to a valid page.", "try", ":", "page", "=", "paginator", ".", "page", "(", "page_num", ")", "except", "PageNotAnInteger", ":", "page", "=", "paginator", ".", "page", "(", "1", ")", "except", "EmptyPage", ":", "page", "=", "paginator", ".", "page", "(", "paginator", ".", "num_pages", ")", "#noinspection PyRedundantParentheses", "return", "(", "paginator", ",", "page", ",", "page", ".", "object_list", ",", "page", ".", "has_other_pages", "(", ")", ")" ]
Returns tuple containing paginator instance, page instance, object list, and whether there are other pages. :param queryset: the queryset instance to paginate. :param page_size: the number of instances per page. :rtype: tuple.
[ "Returns", "tuple", "containing", "paginator", "instance", "page", "instance", "object", "list", "and", "whether", "there", "are", "other", "pages", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L141-L170
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
BaseEditView.form_invalid
def form_invalid(self, form): """ Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ meta = getattr(self.model, '_meta') #noinspection PyUnresolvedReferences messages.error( self.request, _(u'The {0} could not be saved due to errors.').format( meta.verbose_name.lower() ) ) return super(BaseEditView, self).form_invalid(form)
python
def form_invalid(self, form): """ Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ meta = getattr(self.model, '_meta') #noinspection PyUnresolvedReferences messages.error( self.request, _(u'The {0} could not be saved due to errors.').format( meta.verbose_name.lower() ) ) return super(BaseEditView, self).form_invalid(form)
[ "def", "form_invalid", "(", "self", ",", "form", ")", ":", "meta", "=", "getattr", "(", "self", ".", "model", ",", "'_meta'", ")", "#noinspection PyUnresolvedReferences", "messages", ".", "error", "(", "self", ".", "request", ",", "_", "(", "u'The {0} could not be saved due to errors.'", ")", ".", "format", "(", "meta", ".", "verbose_name", ".", "lower", "(", ")", ")", ")", "return", "super", "(", "BaseEditView", ",", "self", ")", ".", "form_invalid", "(", "form", ")" ]
Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse.
[ "Processes", "an", "invalid", "form", "submittal", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L205-L222
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
BaseEditView.form_valid
def form_valid(self, form): """ Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object = form.save() meta = getattr(self.object, '_meta') # Index the object. for backend in get_search_backends(): backend.add(object) #noinspection PyUnresolvedReferences messages.success( self.request, _(u'{0} "{1}" saved.').format( meta.verbose_name, str(self.object) ), buttons=[messages.button( reverse( '{0}:edit'.format(self.url_namespace), args=(self.object.id,) ), _(u'Edit') )] ) return redirect(self.get_success_url())
python
def form_valid(self, form): """ Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object = form.save() meta = getattr(self.object, '_meta') # Index the object. for backend in get_search_backends(): backend.add(object) #noinspection PyUnresolvedReferences messages.success( self.request, _(u'{0} "{1}" saved.').format( meta.verbose_name, str(self.object) ), buttons=[messages.button( reverse( '{0}:edit'.format(self.url_namespace), args=(self.object.id,) ), _(u'Edit') )] ) return redirect(self.get_success_url())
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "#noinspection PyAttributeOutsideInit", "self", ".", "object", "=", "form", ".", "save", "(", ")", "meta", "=", "getattr", "(", "self", ".", "object", ",", "'_meta'", ")", "# Index the object.", "for", "backend", "in", "get_search_backends", "(", ")", ":", "backend", ".", "add", "(", "object", ")", "#noinspection PyUnresolvedReferences", "messages", ".", "success", "(", "self", ".", "request", ",", "_", "(", "u'{0} \"{1}\" saved.'", ")", ".", "format", "(", "meta", ".", "verbose_name", ",", "str", "(", "self", ".", "object", ")", ")", ",", "buttons", "=", "[", "messages", ".", "button", "(", "reverse", "(", "'{0}:edit'", ".", "format", "(", "self", ".", "url_namespace", ")", ",", "args", "=", "(", "self", ".", "object", ".", "id", ",", ")", ")", ",", "_", "(", "u'Edit'", ")", ")", "]", ")", "return", "redirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse.
[ "Processes", "a", "valid", "form", "submittal", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L224-L255
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
BaseEditView.get_success_url
def get_success_url(self): """ Returns redirect URL for valid form submittal. :rtype: str. """ if self.success_url: url = force_text(self.success_url) else: url = reverse('{0}:index'.format(self.url_namespace)) return url
python
def get_success_url(self): """ Returns redirect URL for valid form submittal. :rtype: str. """ if self.success_url: url = force_text(self.success_url) else: url = reverse('{0}:index'.format(self.url_namespace)) return url
[ "def", "get_success_url", "(", "self", ")", ":", "if", "self", ".", "success_url", ":", "url", "=", "force_text", "(", "self", ".", "success_url", ")", "else", ":", "url", "=", "reverse", "(", "'{0}:index'", ".", "format", "(", "self", ".", "url_namespace", ")", ")", "return", "url" ]
Returns redirect URL for valid form submittal. :rtype: str.
[ "Returns", "redirect", "URL", "for", "valid", "form", "submittal", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L257-L268
train
rfosterslo/wagtailplus
wagtailplus/utils/views/crud.py
DeleteView.delete
def delete(self, request, *args, **kwargs): """ Processes deletion of the specified instance. :param request: the request instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object = self.get_object() success_url = self.get_success_url() meta = getattr(self.object, '_meta') self.object.delete() messages.success( request, _(u'{0} "{1}" deleted.').format( meta.verbose_name.lower(), str(self.object) ) ) return redirect(success_url)
python
def delete(self, request, *args, **kwargs): """ Processes deletion of the specified instance. :param request: the request instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object = self.get_object() success_url = self.get_success_url() meta = getattr(self.object, '_meta') self.object.delete() messages.success( request, _(u'{0} "{1}" deleted.').format( meta.verbose_name.lower(), str(self.object) ) ) return redirect(success_url)
[ "def", "delete", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#noinspection PyAttributeOutsideInit", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "meta", "=", "getattr", "(", "self", ".", "object", ",", "'_meta'", ")", "self", ".", "object", ".", "delete", "(", ")", "messages", ".", "success", "(", "request", ",", "_", "(", "u'{0} \"{1}\" deleted.'", ")", ".", "format", "(", "meta", ".", "verbose_name", ".", "lower", "(", ")", ",", "str", "(", "self", ".", "object", ")", ")", ")", "return", "redirect", "(", "success_url", ")" ]
Processes deletion of the specified instance. :param request: the request instance. :rtype: django.http.HttpResponse.
[ "Processes", "deletion", "of", "the", "specified", "instance", "." ]
22cac857175d8a6f77e470751831c14a92ccd768
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/crud.py#L301-L323
train
mozilla/elasticutils
elasticutils/utils.py
chunked
def chunked(iterable, n): """Returns chunks of n length of iterable If len(iterable) % n != 0, then the last chunk will have length less than n. Example: >>> chunked([1, 2, 3, 4, 5], 2) [(1, 2), (3, 4), (5,)] """ iterable = iter(iterable) while 1: t = tuple(islice(iterable, n)) if t: yield t else: return
python
def chunked(iterable, n): """Returns chunks of n length of iterable If len(iterable) % n != 0, then the last chunk will have length less than n. Example: >>> chunked([1, 2, 3, 4, 5], 2) [(1, 2), (3, 4), (5,)] """ iterable = iter(iterable) while 1: t = tuple(islice(iterable, n)) if t: yield t else: return
[ "def", "chunked", "(", "iterable", ",", "n", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "while", "1", ":", "t", "=", "tuple", "(", "islice", "(", "iterable", ",", "n", ")", ")", "if", "t", ":", "yield", "t", "else", ":", "return" ]
Returns chunks of n length of iterable If len(iterable) % n != 0, then the last chunk will have length less than n. Example: >>> chunked([1, 2, 3, 4, 5], 2) [(1, 2), (3, 4), (5,)]
[ "Returns", "chunks", "of", "n", "length", "of", "iterable" ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/utils.py#L33-L52
train
mozilla/elasticutils
elasticutils/utils.py
format_explanation
def format_explanation(explanation, indent=' ', indent_level=0): """Return explanation in an easier to read format Easier to read for me, at least. """ if not explanation: return '' # Note: This is probably a crap implementation, but it's an # interesting starting point for a better formatter. line = ('%s%s %2.4f' % ((indent * indent_level), explanation['description'], explanation['value'])) if 'details' in explanation: details = '\n'.join( [format_explanation(subtree, indent, indent_level + 1) for subtree in explanation['details']]) return line + '\n' + details return line
python
def format_explanation(explanation, indent=' ', indent_level=0): """Return explanation in an easier to read format Easier to read for me, at least. """ if not explanation: return '' # Note: This is probably a crap implementation, but it's an # interesting starting point for a better formatter. line = ('%s%s %2.4f' % ((indent * indent_level), explanation['description'], explanation['value'])) if 'details' in explanation: details = '\n'.join( [format_explanation(subtree, indent, indent_level + 1) for subtree in explanation['details']]) return line + '\n' + details return line
[ "def", "format_explanation", "(", "explanation", ",", "indent", "=", "' '", ",", "indent_level", "=", "0", ")", ":", "if", "not", "explanation", ":", "return", "''", "# Note: This is probably a crap implementation, but it's an", "# interesting starting point for a better formatter.", "line", "=", "(", "'%s%s %2.4f'", "%", "(", "(", "indent", "*", "indent_level", ")", ",", "explanation", "[", "'description'", "]", ",", "explanation", "[", "'value'", "]", ")", ")", "if", "'details'", "in", "explanation", ":", "details", "=", "'\\n'", ".", "join", "(", "[", "format_explanation", "(", "subtree", ",", "indent", ",", "indent_level", "+", "1", ")", "for", "subtree", "in", "explanation", "[", "'details'", "]", "]", ")", "return", "line", "+", "'\\n'", "+", "details", "return", "line" ]
Return explanation in an easier to read format Easier to read for me, at least.
[ "Return", "explanation", "in", "an", "easier", "to", "read", "format" ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/utils.py#L55-L76
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
get_es
def get_es(**overrides): """Return a elasticsearch Elasticsearch object using settings from ``settings.py``. :arg overrides: Allows you to override defaults to create the ElasticSearch object. You can override any of the arguments isted in :py:func:`elasticutils.get_es`. For example, if you wanted to create an ElasticSearch with a longer timeout to a different cluster, you'd do: >>> from elasticutils.contrib.django import get_es >>> es = get_es(urls=['http://some_other_cluster:9200'], timeout=30) """ defaults = { 'urls': settings.ES_URLS, 'timeout': getattr(settings, 'ES_TIMEOUT', 5) } defaults.update(overrides) return base_get_es(**defaults)
python
def get_es(**overrides): """Return a elasticsearch Elasticsearch object using settings from ``settings.py``. :arg overrides: Allows you to override defaults to create the ElasticSearch object. You can override any of the arguments isted in :py:func:`elasticutils.get_es`. For example, if you wanted to create an ElasticSearch with a longer timeout to a different cluster, you'd do: >>> from elasticutils.contrib.django import get_es >>> es = get_es(urls=['http://some_other_cluster:9200'], timeout=30) """ defaults = { 'urls': settings.ES_URLS, 'timeout': getattr(settings, 'ES_TIMEOUT', 5) } defaults.update(overrides) return base_get_es(**defaults)
[ "def", "get_es", "(", "*", "*", "overrides", ")", ":", "defaults", "=", "{", "'urls'", ":", "settings", ".", "ES_URLS", ",", "'timeout'", ":", "getattr", "(", "settings", ",", "'ES_TIMEOUT'", ",", "5", ")", "}", "defaults", ".", "update", "(", "overrides", ")", "return", "base_get_es", "(", "*", "*", "defaults", ")" ]
Return a elasticsearch Elasticsearch object using settings from ``settings.py``. :arg overrides: Allows you to override defaults to create the ElasticSearch object. You can override any of the arguments isted in :py:func:`elasticutils.get_es`. For example, if you wanted to create an ElasticSearch with a longer timeout to a different cluster, you'd do: >>> from elasticutils.contrib.django import get_es >>> es = get_es(urls=['http://some_other_cluster:9200'], timeout=30)
[ "Return", "a", "elasticsearch", "Elasticsearch", "object", "using", "settings", "from", "settings", ".", "py", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L26-L47
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
es_required
def es_required(fun): """Wrap a callable and return None if ES_DISABLED is False. This also adds an additional `es` argument to the callable giving you an ElasticSearch instance to use. """ @wraps(fun) def wrapper(*args, **kw): if getattr(settings, 'ES_DISABLED', False): log.debug('Search disabled for %s.' % fun) return return fun(*args, es=get_es(), **kw) return wrapper
python
def es_required(fun): """Wrap a callable and return None if ES_DISABLED is False. This also adds an additional `es` argument to the callable giving you an ElasticSearch instance to use. """ @wraps(fun) def wrapper(*args, **kw): if getattr(settings, 'ES_DISABLED', False): log.debug('Search disabled for %s.' % fun) return return fun(*args, es=get_es(), **kw) return wrapper
[ "def", "es_required", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "getattr", "(", "settings", ",", "'ES_DISABLED'", ",", "False", ")", ":", "log", ".", "debug", "(", "'Search disabled for %s.'", "%", "fun", ")", "return", "return", "fun", "(", "*", "args", ",", "es", "=", "get_es", "(", ")", ",", "*", "*", "kw", ")", "return", "wrapper" ]
Wrap a callable and return None if ES_DISABLED is False. This also adds an additional `es` argument to the callable giving you an ElasticSearch instance to use.
[ "Wrap", "a", "callable", "and", "return", "None", "if", "ES_DISABLED", "is", "False", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L50-L64
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
S.get_es
def get_es(self, default_builder=get_es): """Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes into account settings in ``settings.py``. """ return super(S, self).get_es(default_builder=default_builder)
python
def get_es(self, default_builder=get_es): """Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes into account settings in ``settings.py``. """ return super(S, self).get_es(default_builder=default_builder)
[ "def", "get_es", "(", "self", ",", "default_builder", "=", "get_es", ")", ":", "return", "super", "(", "S", ",", "self", ")", ".", "get_es", "(", "default_builder", "=", "default_builder", ")" ]
Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes into account settings in ``settings.py``.
[ "Returns", "the", "elasticsearch", "Elasticsearch", "object", "to", "use", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L165-L172
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
S.get_indexes
def get_indexes(self, default_indexes=None): """Returns the list of indexes to act on based on ES_INDEXES setting """ doctype = self.type.get_mapping_type_name() indexes = (settings.ES_INDEXES.get(doctype) or settings.ES_INDEXES['default']) if isinstance(indexes, six.string_types): indexes = [indexes] return super(S, self).get_indexes(default_indexes=indexes)
python
def get_indexes(self, default_indexes=None): """Returns the list of indexes to act on based on ES_INDEXES setting """ doctype = self.type.get_mapping_type_name() indexes = (settings.ES_INDEXES.get(doctype) or settings.ES_INDEXES['default']) if isinstance(indexes, six.string_types): indexes = [indexes] return super(S, self).get_indexes(default_indexes=indexes)
[ "def", "get_indexes", "(", "self", ",", "default_indexes", "=", "None", ")", ":", "doctype", "=", "self", ".", "type", ".", "get_mapping_type_name", "(", ")", "indexes", "=", "(", "settings", ".", "ES_INDEXES", ".", "get", "(", "doctype", ")", "or", "settings", ".", "ES_INDEXES", "[", "'default'", "]", ")", "if", "isinstance", "(", "indexes", ",", "six", ".", "string_types", ")", ":", "indexes", "=", "[", "indexes", "]", "return", "super", "(", "S", ",", "self", ")", ".", "get_indexes", "(", "default_indexes", "=", "indexes", ")" ]
Returns the list of indexes to act on based on ES_INDEXES setting
[ "Returns", "the", "list", "of", "indexes", "to", "act", "on", "based", "on", "ES_INDEXES", "setting" ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L174-L183
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
S.get_doctypes
def get_doctypes(self, default_doctypes=None): """Returns the doctypes (or mapping type names) to use.""" doctypes = self.type.get_mapping_type_name() if isinstance(doctypes, six.string_types): doctypes = [doctypes] return super(S, self).get_doctypes(default_doctypes=doctypes)
python
def get_doctypes(self, default_doctypes=None): """Returns the doctypes (or mapping type names) to use.""" doctypes = self.type.get_mapping_type_name() if isinstance(doctypes, six.string_types): doctypes = [doctypes] return super(S, self).get_doctypes(default_doctypes=doctypes)
[ "def", "get_doctypes", "(", "self", ",", "default_doctypes", "=", "None", ")", ":", "doctypes", "=", "self", ".", "type", ".", "get_mapping_type_name", "(", ")", "if", "isinstance", "(", "doctypes", ",", "six", ".", "string_types", ")", ":", "doctypes", "=", "[", "doctypes", "]", "return", "super", "(", "S", ",", "self", ")", ".", "get_doctypes", "(", "default_doctypes", "=", "doctypes", ")" ]
Returns the doctypes (or mapping type names) to use.
[ "Returns", "the", "doctypes", "(", "or", "mapping", "type", "names", ")", "to", "use", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L185-L190
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
MappingType.get_index
def get_index(cls): """Gets the index for this model. The index for this model is specified in `settings.ES_INDEXES` which is a dict of mapping type -> index name. By default, this uses `.get_mapping_type()` to determine the mapping and returns the value in `settings.ES_INDEXES` for that or ``settings.ES_INDEXES['default']``. Override this to compute it differently. :returns: index name to use """ indexes = settings.ES_INDEXES index = indexes.get(cls.get_mapping_type_name()) or indexes['default'] if not (isinstance(index, six.string_types)): # FIXME - not sure what to do here, but we only want one # index and somehow this isn't one index. index = index[0] return index
python
def get_index(cls): """Gets the index for this model. The index for this model is specified in `settings.ES_INDEXES` which is a dict of mapping type -> index name. By default, this uses `.get_mapping_type()` to determine the mapping and returns the value in `settings.ES_INDEXES` for that or ``settings.ES_INDEXES['default']``. Override this to compute it differently. :returns: index name to use """ indexes = settings.ES_INDEXES index = indexes.get(cls.get_mapping_type_name()) or indexes['default'] if not (isinstance(index, six.string_types)): # FIXME - not sure what to do here, but we only want one # index and somehow this isn't one index. index = index[0] return index
[ "def", "get_index", "(", "cls", ")", ":", "indexes", "=", "settings", ".", "ES_INDEXES", "index", "=", "indexes", ".", "get", "(", "cls", ".", "get_mapping_type_name", "(", ")", ")", "or", "indexes", "[", "'default'", "]", "if", "not", "(", "isinstance", "(", "index", ",", "six", ".", "string_types", ")", ")", ":", "# FIXME - not sure what to do here, but we only want one", "# index and somehow this isn't one index.", "index", "=", "index", "[", "0", "]", "return", "index" ]
Gets the index for this model. The index for this model is specified in `settings.ES_INDEXES` which is a dict of mapping type -> index name. By default, this uses `.get_mapping_type()` to determine the mapping and returns the value in `settings.ES_INDEXES` for that or ``settings.ES_INDEXES['default']``. Override this to compute it differently. :returns: index name to use
[ "Gets", "the", "index", "for", "this", "model", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L225-L246
train
mozilla/elasticutils
elasticutils/contrib/django/__init__.py
Indexable.get_indexable
def get_indexable(cls): """Returns the queryset of ids of all things to be indexed. Defaults to:: cls.get_model().objects.order_by('id').values_list( 'id', flat=True) :returns: iterable of ids of objects to be indexed """ model = cls.get_model() return model.objects.order_by('id').values_list('id', flat=True)
python
def get_indexable(cls): """Returns the queryset of ids of all things to be indexed. Defaults to:: cls.get_model().objects.order_by('id').values_list( 'id', flat=True) :returns: iterable of ids of objects to be indexed """ model = cls.get_model() return model.objects.order_by('id').values_list('id', flat=True)
[ "def", "get_indexable", "(", "cls", ")", ":", "model", "=", "cls", ".", "get_model", "(", ")", "return", "model", ".", "objects", ".", "order_by", "(", "'id'", ")", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")" ]
Returns the queryset of ids of all things to be indexed. Defaults to:: cls.get_model().objects.order_by('id').values_list( 'id', flat=True) :returns: iterable of ids of objects to be indexed
[ "Returns", "the", "queryset", "of", "ids", "of", "all", "things", "to", "be", "indexed", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L298-L310
train
mozilla/elasticutils
elasticutils/__init__.py
get_es
def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings): """Create an elasticsearch `Elasticsearch` object and return it. This will aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will return the same `Elasticsearch` object 2. if you pass different argument values to `get_es()`, then it will return different `Elasticsearch` object 3. it caches each `Elasticsearch` object that gets created 4. if you pass in `force_new=True`, then you are guaranteed to get a fresh `Elasticsearch` object AND that object will not be cached :arg urls: list of uris; Elasticsearch hosts to connect to, defaults to ``['http://localhost:9200']`` :arg timeout: int; the timeout in seconds, defaults to 5 :arg force_new: Forces get_es() to generate a new Elasticsearch object rather than pulling it from cache. :arg settings: other settings to pass into Elasticsearch constructor; See `<http://elasticsearch-py.readthedocs.org/>`_ for more details. Examples:: # Returns cached Elasticsearch object es = get_es() # Returns a new Elasticsearch object es = get_es(force_new=True) es = get_es(urls=['localhost']) es = get_es(urls=['localhost:9200'], timeout=10, max_retries=3) """ # Cheap way of de-None-ifying things urls = urls or DEFAULT_URLS # v0.7: Check for 'hosts' instead of 'urls'. Take this out in v1.0. if 'hosts' in settings: raise DeprecationWarning('"hosts" is deprecated in favor of "urls".') if not force_new: key = _build_key(urls, timeout, **settings) if key in _cached_elasticsearch: return _cached_elasticsearch[key] es = Elasticsearch(urls, timeout=timeout, **settings) if not force_new: # We don't need to rebuild the key here since we built it in # the previous if block, so it's in the namespace. Having said # that, this is a little ew. _cached_elasticsearch[key] = es return es
python
def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings): """Create an elasticsearch `Elasticsearch` object and return it. This will aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will return the same `Elasticsearch` object 2. if you pass different argument values to `get_es()`, then it will return different `Elasticsearch` object 3. it caches each `Elasticsearch` object that gets created 4. if you pass in `force_new=True`, then you are guaranteed to get a fresh `Elasticsearch` object AND that object will not be cached :arg urls: list of uris; Elasticsearch hosts to connect to, defaults to ``['http://localhost:9200']`` :arg timeout: int; the timeout in seconds, defaults to 5 :arg force_new: Forces get_es() to generate a new Elasticsearch object rather than pulling it from cache. :arg settings: other settings to pass into Elasticsearch constructor; See `<http://elasticsearch-py.readthedocs.org/>`_ for more details. Examples:: # Returns cached Elasticsearch object es = get_es() # Returns a new Elasticsearch object es = get_es(force_new=True) es = get_es(urls=['localhost']) es = get_es(urls=['localhost:9200'], timeout=10, max_retries=3) """ # Cheap way of de-None-ifying things urls = urls or DEFAULT_URLS # v0.7: Check for 'hosts' instead of 'urls'. Take this out in v1.0. if 'hosts' in settings: raise DeprecationWarning('"hosts" is deprecated in favor of "urls".') if not force_new: key = _build_key(urls, timeout, **settings) if key in _cached_elasticsearch: return _cached_elasticsearch[key] es = Elasticsearch(urls, timeout=timeout, **settings) if not force_new: # We don't need to rebuild the key here since we built it in # the previous if block, so it's in the namespace. Having said # that, this is a little ew. _cached_elasticsearch[key] = es return es
[ "def", "get_es", "(", "urls", "=", "None", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "force_new", "=", "False", ",", "*", "*", "settings", ")", ":", "# Cheap way of de-None-ifying things", "urls", "=", "urls", "or", "DEFAULT_URLS", "# v0.7: Check for 'hosts' instead of 'urls'. Take this out in v1.0.", "if", "'hosts'", "in", "settings", ":", "raise", "DeprecationWarning", "(", "'\"hosts\" is deprecated in favor of \"urls\".'", ")", "if", "not", "force_new", ":", "key", "=", "_build_key", "(", "urls", ",", "timeout", ",", "*", "*", "settings", ")", "if", "key", "in", "_cached_elasticsearch", ":", "return", "_cached_elasticsearch", "[", "key", "]", "es", "=", "Elasticsearch", "(", "urls", ",", "timeout", "=", "timeout", ",", "*", "*", "settings", ")", "if", "not", "force_new", ":", "# We don't need to rebuild the key here since we built it in", "# the previous if block, so it's in the namespace. Having said", "# that, this is a little ew.", "_cached_elasticsearch", "[", "key", "]", "=", "es", "return", "es" ]
Create an elasticsearch `Elasticsearch` object and return it. This will aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will return the same `Elasticsearch` object 2. if you pass different argument values to `get_es()`, then it will return different `Elasticsearch` object 3. it caches each `Elasticsearch` object that gets created 4. if you pass in `force_new=True`, then you are guaranteed to get a fresh `Elasticsearch` object AND that object will not be cached :arg urls: list of uris; Elasticsearch hosts to connect to, defaults to ``['http://localhost:9200']`` :arg timeout: int; the timeout in seconds, defaults to 5 :arg force_new: Forces get_es() to generate a new Elasticsearch object rather than pulling it from cache. :arg settings: other settings to pass into Elasticsearch constructor; See `<http://elasticsearch-py.readthedocs.org/>`_ for more details. Examples:: # Returns cached Elasticsearch object es = get_es() # Returns a new Elasticsearch object es = get_es(force_new=True) es = get_es(urls=['localhost']) es = get_es(urls=['localhost:9200'], timeout=10, max_retries=3)
[ "Create", "an", "elasticsearch", "Elasticsearch", "object", "and", "return", "it", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L109-L167
train
mozilla/elasticutils
elasticutils/__init__.py
_facet_counts
def _facet_counts(items): """Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts keyed on the facet name provided in the original query. """ facets = {} for name, data in items: facets[name] = FacetResult(name, data) return facets
python
def _facet_counts(items): """Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts keyed on the facet name provided in the original query. """ facets = {} for name, data in items: facets[name] = FacetResult(name, data) return facets
[ "def", "_facet_counts", "(", "items", ")", ":", "facets", "=", "{", "}", "for", "name", ",", "data", "in", "items", ":", "facets", "[", "name", "]", "=", "FacetResult", "(", "name", ",", "data", ")", "return", "facets" ]
Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts keyed on the facet name provided in the original query.
[ "Returns", "facet", "counts", "as", "dict", "." ]
b880cc5d51fb1079b0581255ec664c1ec934656e
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L203-L214
train