id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
234,200
getsentry/sentry-python
sentry_sdk/hub.py
Hub.bind_client
def bind_client(self, new): """Binds a new client to the hub.""" top = self._stack[-1] self._stack[-1] = (new, top[1])
python
def bind_client(self, new): top = self._stack[-1] self._stack[-1] = (new, top[1])
[ "def", "bind_client", "(", "self", ",", "new", ")", ":", "top", "=", "self", ".", "_stack", "[", "-", "1", "]", "self", ".", "_stack", "[", "-", "1", "]", "=", "(", "new", ",", "top", "[", "1", "]", ")" ]
Binds a new client to the hub.
[ "Binds", "a", "new", "client", "to", "the", "hub", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L248-L251
234,201
getsentry/sentry-python
sentry_sdk/hub.py
Hub.capture_event
def capture_event(self, event, hint=None): # type: (Dict[str, Any], Dict[str, Any]) -> Optional[str] """Captures an event. The return value is the ID of the event. The event is a dictionary following the Sentry v7/v8 protocol specification. Optionally an event hint dict can be passed that is used by processors to extract additional information from it. Typically the event hint object would contain exception information. """ client, scope = self._stack[-1] if client is not None: rv = client.capture_event(event, hint, scope) if rv is not None: self._last_event_id = rv return rv return None
python
def capture_event(self, event, hint=None): # type: (Dict[str, Any], Dict[str, Any]) -> Optional[str] client, scope = self._stack[-1] if client is not None: rv = client.capture_event(event, hint, scope) if rv is not None: self._last_event_id = rv return rv return None
[ "def", "capture_event", "(", "self", ",", "event", ",", "hint", "=", "None", ")", ":", "# type: (Dict[str, Any], Dict[str, Any]) -> Optional[str]", "client", ",", "scope", "=", "self", ".", "_stack", "[", "-", "1", "]", "if", "client", "is", "not", "None", "...
Captures an event. The return value is the ID of the event. The event is a dictionary following the Sentry v7/v8 protocol specification. Optionally an event hint dict can be passed that is used by processors to extract additional information from it. Typically the event hint object would contain exception information.
[ "Captures", "an", "event", ".", "The", "return", "value", "is", "the", "ID", "of", "the", "event", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L253-L268
234,202
getsentry/sentry-python
sentry_sdk/hub.py
Hub.capture_message
def capture_message(self, message, level=None): # type: (str, Optional[Any]) -> Optional[str] """Captures a message. The message is just a string. If no level is provided the default level is `info`. """ if self.client is None: return None if level is None: level = "info" return self.capture_event({"message": message, "level": level})
python
def capture_message(self, message, level=None): # type: (str, Optional[Any]) -> Optional[str] if self.client is None: return None if level is None: level = "info" return self.capture_event({"message": message, "level": level})
[ "def", "capture_message", "(", "self", ",", "message", ",", "level", "=", "None", ")", ":", "# type: (str, Optional[Any]) -> Optional[str]", "if", "self", ".", "client", "is", "None", ":", "return", "None", "if", "level", "is", "None", ":", "level", "=", "\"...
Captures a message. The message is just a string. If no level is provided the default level is `info`.
[ "Captures", "a", "message", ".", "The", "message", "is", "just", "a", "string", ".", "If", "no", "level", "is", "provided", "the", "default", "level", "is", "info", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L270-L279
234,203
getsentry/sentry-python
sentry_sdk/hub.py
Hub.capture_exception
def capture_exception(self, error=None): # type: (Optional[BaseException]) -> Optional[str] """Captures an exception. The argument passed can be `None` in which case the last exception will be reported, otherwise an exception object or an `exc_info` tuple. """ client = self.client if client is None: return None if error is None: exc_info = sys.exc_info() else: exc_info = exc_info_from_error(error) event, hint = event_from_exception(exc_info, client_options=client.options) try: return self.capture_event(event, hint=hint) except Exception: self._capture_internal_exception(sys.exc_info()) return None
python
def capture_exception(self, error=None): # type: (Optional[BaseException]) -> Optional[str] client = self.client if client is None: return None if error is None: exc_info = sys.exc_info() else: exc_info = exc_info_from_error(error) event, hint = event_from_exception(exc_info, client_options=client.options) try: return self.capture_event(event, hint=hint) except Exception: self._capture_internal_exception(sys.exc_info()) return None
[ "def", "capture_exception", "(", "self", ",", "error", "=", "None", ")", ":", "# type: (Optional[BaseException]) -> Optional[str]", "client", "=", "self", ".", "client", "if", "client", "is", "None", ":", "return", "None", "if", "error", "is", "None", ":", "ex...
Captures an exception. The argument passed can be `None` in which case the last exception will be reported, otherwise an exception object or an `exc_info` tuple.
[ "Captures", "an", "exception", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L281-L303
234,204
getsentry/sentry-python
sentry_sdk/hub.py
Hub.push_scope
def push_scope(self, callback=None): # noqa """Pushes a new layer on the scope stack. Returns a context manager that should be used to pop the scope again. Alternatively a callback can be provided that is executed in the context of the scope. """ if callback is not None: with self.push_scope() as scope: callback(scope) return None client, scope = self._stack[-1] new_layer = (client, copy.copy(scope)) self._stack.append(new_layer) return _ScopeManager(self)
python
def push_scope(self, callback=None): # noqa if callback is not None: with self.push_scope() as scope: callback(scope) return None client, scope = self._stack[-1] new_layer = (client, copy.copy(scope)) self._stack.append(new_layer) return _ScopeManager(self)
[ "def", "push_scope", "(", "self", ",", "callback", "=", "None", ")", ":", "# noqa", "if", "callback", "is", "not", "None", ":", "with", "self", ".", "push_scope", "(", ")", "as", "scope", ":", "callback", "(", "scope", ")", "return", "None", "client", ...
Pushes a new layer on the scope stack. Returns a context manager that should be used to pop the scope again. Alternatively a callback can be provided that is executed in the context of the scope.
[ "Pushes", "a", "new", "layer", "on", "the", "scope", "stack", ".", "Returns", "a", "context", "manager", "that", "should", "be", "used", "to", "pop", "the", "scope", "again", ".", "Alternatively", "a", "callback", "can", "be", "provided", "that", "is", "...
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L357-L372
234,205
getsentry/sentry-python
sentry_sdk/hub.py
Hub.configure_scope
def configure_scope(self, callback=None): # noqa """Reconfigures the scope.""" client, scope = self._stack[-1] if callback is not None: if client is not None: callback(scope) return None @contextmanager def inner(): if client is not None: yield scope else: yield Scope() return inner()
python
def configure_scope(self, callback=None): # noqa client, scope = self._stack[-1] if callback is not None: if client is not None: callback(scope) return None @contextmanager def inner(): if client is not None: yield scope else: yield Scope() return inner()
[ "def", "configure_scope", "(", "self", ",", "callback", "=", "None", ")", ":", "# noqa", "client", ",", "scope", "=", "self", ".", "_stack", "[", "-", "1", "]", "if", "callback", "is", "not", "None", ":", "if", "client", "is", "not", "None", ":", "...
Reconfigures the scope.
[ "Reconfigures", "the", "scope", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L393-L410
234,206
getsentry/sentry-python
sentry_sdk/hub.py
Hub.flush
def flush(self, timeout=None, callback=None): """Alias for self.client.flush""" client, scope = self._stack[-1] if client is not None: return client.flush(timeout=timeout, callback=callback)
python
def flush(self, timeout=None, callback=None): client, scope = self._stack[-1] if client is not None: return client.flush(timeout=timeout, callback=callback)
[ "def", "flush", "(", "self", ",", "timeout", "=", "None", ",", "callback", "=", "None", ")", ":", "client", ",", "scope", "=", "self", ".", "_stack", "[", "-", "1", "]", "if", "client", "is", "not", "None", ":", "return", "client", ".", "flush", ...
Alias for self.client.flush
[ "Alias", "for", "self", ".", "client", ".", "flush" ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L412-L416
234,207
getsentry/sentry-python
sentry_sdk/client.py
Client.capture_event
def capture_event(self, event, hint=None, scope=None): # type: (Dict[str, Any], Any, Scope) -> Optional[str] """Captures an event. This takes the ready made event and an optoinal hint and scope. The hint is internally used to further customize the representation of the error. When provided it's a dictionary of optional information such as exception info. If the transport is not set nothing happens, otherwise the return value of this function will be the ID of the captured event. """ if self.transport is None: return None if hint is None: hint = {} rv = event.get("event_id") if rv is None: event["event_id"] = rv = uuid.uuid4().hex if not self._should_capture(event, hint, scope): return None event = self._prepare_event(event, hint, scope) # type: ignore if event is None: return None self.transport.capture_event(event) return rv
python
def capture_event(self, event, hint=None, scope=None): # type: (Dict[str, Any], Any, Scope) -> Optional[str] if self.transport is None: return None if hint is None: hint = {} rv = event.get("event_id") if rv is None: event["event_id"] = rv = uuid.uuid4().hex if not self._should_capture(event, hint, scope): return None event = self._prepare_event(event, hint, scope) # type: ignore if event is None: return None self.transport.capture_event(event) return rv
[ "def", "capture_event", "(", "self", ",", "event", ",", "hint", "=", "None", ",", "scope", "=", "None", ")", ":", "# type: (Dict[str, Any], Any, Scope) -> Optional[str]", "if", "self", ".", "transport", "is", "None", ":", "return", "None", "if", "hint", "is", ...
Captures an event. This takes the ready made event and an optoinal hint and scope. The hint is internally used to further customize the representation of the error. When provided it's a dictionary of optional information such as exception info. If the transport is not set nothing happens, otherwise the return value of this function will be the ID of the captured event.
[ "Captures", "an", "event", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/client.py#L206-L231
234,208
getsentry/sentry-python
sentry_sdk/client.py
Client.flush
def flush(self, timeout=None, callback=None): """ Wait `timeout` seconds for the current events to be sent. If no `timeout` is provided, the `shutdown_timeout` option value is used. The `callback` is invoked with two arguments: the number of pending events and the configured timeout. For instance the default atexit integration will use this to render out a message on stderr. """ if self.transport is not None: if timeout is None: timeout = self.options["shutdown_timeout"] self.transport.flush(timeout=timeout, callback=callback)
python
def flush(self, timeout=None, callback=None): if self.transport is not None: if timeout is None: timeout = self.options["shutdown_timeout"] self.transport.flush(timeout=timeout, callback=callback)
[ "def", "flush", "(", "self", ",", "timeout", "=", "None", ",", "callback", "=", "None", ")", ":", "if", "self", ".", "transport", "is", "not", "None", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "options", "[", "\"shutdown_t...
Wait `timeout` seconds for the current events to be sent. If no `timeout` is provided, the `shutdown_timeout` option value is used. The `callback` is invoked with two arguments: the number of pending events and the configured timeout. For instance the default atexit integration will use this to render out a message on stderr.
[ "Wait", "timeout", "seconds", "for", "the", "current", "events", "to", "be", "sent", ".", "If", "no", "timeout", "is", "provided", "the", "shutdown_timeout", "option", "value", "is", "used", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/client.py#L243-L255
234,209
getsentry/sentry-python
sentry_sdk/integrations/__init__.py
setup_integrations
def setup_integrations(integrations, with_defaults=True): # type: (List[Integration], bool) -> Dict[str, Integration] """Given a list of integration instances this installs them all. When `with_defaults` is set to `True` then all default integrations are added unless they were already provided before. """ integrations = dict( (integration.identifier, integration) for integration in integrations or () ) logger.debug("Setting up integrations (with default = %s)", with_defaults) if with_defaults: for integration_cls in iter_default_integrations(): if integration_cls.identifier not in integrations: instance = integration_cls() integrations[instance.identifier] = instance for identifier, integration in iteritems(integrations): with _installer_lock: if identifier not in _installed_integrations: logger.debug( "Setting up previously not enabled integration %s", identifier ) try: type(integration).setup_once() except NotImplementedError: if getattr(integration, "install", None) is not None: logger.warn( "Integration %s: The install method is " "deprecated. Use `setup_once`.", identifier, ) integration.install() else: raise _installed_integrations.add(identifier) for identifier in integrations: logger.debug("Enabling integration %s", identifier) return integrations
python
def setup_integrations(integrations, with_defaults=True): # type: (List[Integration], bool) -> Dict[str, Integration] integrations = dict( (integration.identifier, integration) for integration in integrations or () ) logger.debug("Setting up integrations (with default = %s)", with_defaults) if with_defaults: for integration_cls in iter_default_integrations(): if integration_cls.identifier not in integrations: instance = integration_cls() integrations[instance.identifier] = instance for identifier, integration in iteritems(integrations): with _installer_lock: if identifier not in _installed_integrations: logger.debug( "Setting up previously not enabled integration %s", identifier ) try: type(integration).setup_once() except NotImplementedError: if getattr(integration, "install", None) is not None: logger.warn( "Integration %s: The install method is " "deprecated. Use `setup_once`.", identifier, ) integration.install() else: raise _installed_integrations.add(identifier) for identifier in integrations: logger.debug("Enabling integration %s", identifier) return integrations
[ "def", "setup_integrations", "(", "integrations", ",", "with_defaults", "=", "True", ")", ":", "# type: (List[Integration], bool) -> Dict[str, Integration]", "integrations", "=", "dict", "(", "(", "integration", ".", "identifier", ",", "integration", ")", "for", "integr...
Given a list of integration instances this installs them all. When `with_defaults` is set to `True` then all default integrations are added unless they were already provided before.
[ "Given", "a", "list", "of", "integration", "instances", "this", "installs", "them", "all", ".", "When", "with_defaults", "is", "set", "to", "True", "then", "all", "default", "integrations", "are", "added", "unless", "they", "were", "already", "provided", "befo...
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/__init__.py#L57-L98
234,210
getsentry/sentry-python
sentry_sdk/scope.py
Scope.clear
def clear(self): # type: () -> None """Clears the entire scope.""" self._level = None self._fingerprint = None self._transaction = None self._user = None self._tags = {} # type: Dict[str, Any] self._contexts = {} # type: Dict[str, Dict] self._extras = {} # type: Dict[str, Any] self.clear_breadcrumbs() self._should_capture = True self._span = None
python
def clear(self): # type: () -> None self._level = None self._fingerprint = None self._transaction = None self._user = None self._tags = {} # type: Dict[str, Any] self._contexts = {} # type: Dict[str, Dict] self._extras = {} # type: Dict[str, Any] self.clear_breadcrumbs() self._should_capture = True self._span = None
[ "def", "clear", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_level", "=", "None", "self", ".", "_fingerprint", "=", "None", "self", ".", "_transaction", "=", "None", "self", ".", "_user", "=", "None", "self", ".", "_tags", "=", "{", "}",...
Clears the entire scope.
[ "Clears", "the", "entire", "scope", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/scope.py#L120-L135
234,211
getsentry/sentry-python
sentry_sdk/scope.py
Scope.add_error_processor
def add_error_processor(self, func, cls=None): # type: (Callable, Optional[type]) -> None """"Register a scope local error processor on the scope. The error processor works similar to an event processor but is invoked with the original exception info triple as second argument. """ if cls is not None: real_func = func def func(event, exc_info): try: is_inst = isinstance(exc_info[1], cls) except Exception: is_inst = False if is_inst: return real_func(event, exc_info) return event self._error_processors.append(func)
python
def add_error_processor(self, func, cls=None): # type: (Callable, Optional[type]) -> None "if cls is not None: real_func = func def func(event, exc_info): try: is_inst = isinstance(exc_info[1], cls) except Exception: is_inst = False if is_inst: return real_func(event, exc_info) return event self._error_processors.append(func)
[ "def", "add_error_processor", "(", "self", ",", "func", ",", "cls", "=", "None", ")", ":", "# type: (Callable, Optional[type]) -> None", "if", "cls", "is", "not", "None", ":", "real_func", "=", "func", "def", "func", "(", "event", ",", "exc_info", ")", ":", ...
Register a scope local error processor on the scope. The error processor works similar to an event processor but is invoked with the original exception info triple as second argument.
[ "Register", "a", "scope", "local", "error", "processor", "on", "the", "scope", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/scope.py#L150-L169
234,212
getsentry/sentry-python
sentry_sdk/scope.py
Scope.apply_to_event
def apply_to_event(self, event, hint=None): # type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]] """Applies the information contained on the scope to the given event.""" def _drop(event, cause, ty): # type: (Dict[str, Any], Callable, str) -> Optional[Any] logger.info("%s (%s) dropped event (%s)", ty, cause, event) return None if self._level is not None: event["level"] = self._level event.setdefault("breadcrumbs", []).extend(self._breadcrumbs) if event.get("user") is None and self._user is not None: event["user"] = self._user if event.get("transaction") is None and self._transaction is not None: event["transaction"] = self._transaction if event.get("fingerprint") is None and self._fingerprint is not None: event["fingerprint"] = self._fingerprint if self._extras: event.setdefault("extra", {}).update(object_to_json(self._extras)) if self._tags: event.setdefault("tags", {}).update(self._tags) if self._contexts: event.setdefault("contexts", {}).update(self._contexts) if self._span is not None: event.setdefault("contexts", {})["trace"] = { "trace_id": self._span.trace_id, "span_id": self._span.span_id, } exc_info = hint.get("exc_info") if hint is not None else None if exc_info is not None: for processor in self._error_processors: new_event = processor(event, exc_info) if new_event is None: return _drop(event, processor, "error processor") event = new_event for processor in chain(global_event_processors, self._event_processors): new_event = event with capture_internal_exceptions(): new_event = processor(event, hint) if new_event is None: return _drop(event, processor, "event processor") event = new_event return event
python
def apply_to_event(self, event, hint=None): # type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]] def _drop(event, cause, ty): # type: (Dict[str, Any], Callable, str) -> Optional[Any] logger.info("%s (%s) dropped event (%s)", ty, cause, event) return None if self._level is not None: event["level"] = self._level event.setdefault("breadcrumbs", []).extend(self._breadcrumbs) if event.get("user") is None and self._user is not None: event["user"] = self._user if event.get("transaction") is None and self._transaction is not None: event["transaction"] = self._transaction if event.get("fingerprint") is None and self._fingerprint is not None: event["fingerprint"] = self._fingerprint if self._extras: event.setdefault("extra", {}).update(object_to_json(self._extras)) if self._tags: event.setdefault("tags", {}).update(self._tags) if self._contexts: event.setdefault("contexts", {}).update(self._contexts) if self._span is not None: event.setdefault("contexts", {})["trace"] = { "trace_id": self._span.trace_id, "span_id": self._span.span_id, } exc_info = hint.get("exc_info") if hint is not None else None if exc_info is not None: for processor in self._error_processors: new_event = processor(event, exc_info) if new_event is None: return _drop(event, processor, "error processor") event = new_event for processor in chain(global_event_processors, self._event_processors): new_event = event with capture_internal_exceptions(): new_event = processor(event, hint) if new_event is None: return _drop(event, processor, "event processor") event = new_event return event
[ "def", "apply_to_event", "(", "self", ",", "event", ",", "hint", "=", "None", ")", ":", "# type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]]", "def", "_drop", "(", "event", ",", "cause", ",", "ty", ")", ":", "# type: (Dict[str, Any], Callable, str) -> O...
Applies the information contained on the scope to the given event.
[ "Applies", "the", "information", "contained", "on", "the", "scope", "to", "the", "given", "event", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/scope.py#L172-L225
234,213
getsentry/sentry-python
sentry_sdk/integrations/atexit.py
default_callback
def default_callback(pending, timeout): """This is the default shutdown callback that is set on the options. It prints out a message to stderr that informs the user that some events are still pending and the process is waiting for them to flush out. """ def echo(msg): sys.stderr.write(msg + "\n") echo("Sentry is attempting to send %i pending error messages" % pending) echo("Waiting up to %s seconds" % timeout) echo("Press Ctrl-%s to quit" % (os.name == "nt" and "Break" or "C")) sys.stderr.flush()
python
def default_callback(pending, timeout): def echo(msg): sys.stderr.write(msg + "\n") echo("Sentry is attempting to send %i pending error messages" % pending) echo("Waiting up to %s seconds" % timeout) echo("Press Ctrl-%s to quit" % (os.name == "nt" and "Break" or "C")) sys.stderr.flush()
[ "def", "default_callback", "(", "pending", ",", "timeout", ")", ":", "def", "echo", "(", "msg", ")", ":", "sys", ".", "stderr", ".", "write", "(", "msg", "+", "\"\\n\"", ")", "echo", "(", "\"Sentry is attempting to send %i pending error messages\"", "%", "pend...
This is the default shutdown callback that is set on the options. It prints out a message to stderr that informs the user that some events are still pending and the process is waiting for them to flush out.
[ "This", "is", "the", "default", "shutdown", "callback", "that", "is", "set", "on", "the", "options", ".", "It", "prints", "out", "a", "message", "to", "stderr", "that", "informs", "the", "user", "that", "some", "events", "are", "still", "pending", "and", ...
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/atexit.py#L16-L28
234,214
getsentry/sentry-python
sentry_sdk/integrations/wsgi.py
get_host
def get_host(environ): # type: (Dict[str, str]) -> str """Return the host for the given WSGI environment. Yanked from Werkzeug.""" if environ.get("HTTP_HOST"): rv = environ["HTTP_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"): rv = rv[:-4] elif environ.get("SERVER_NAME"): rv = environ["SERVER_NAME"] if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in ( ("https", "443"), ("http", "80"), ): rv += ":" + environ["SERVER_PORT"] else: # In spite of the WSGI spec, SERVER_NAME might not be present. rv = "unknown" return rv
python
def get_host(environ): # type: (Dict[str, str]) -> str if environ.get("HTTP_HOST"): rv = environ["HTTP_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"): rv = rv[:-4] elif environ.get("SERVER_NAME"): rv = environ["SERVER_NAME"] if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in ( ("https", "443"), ("http", "80"), ): rv += ":" + environ["SERVER_PORT"] else: # In spite of the WSGI spec, SERVER_NAME might not be present. rv = "unknown" return rv
[ "def", "get_host", "(", "environ", ")", ":", "# type: (Dict[str, str]) -> str", "if", "environ", ".", "get", "(", "\"HTTP_HOST\"", ")", ":", "rv", "=", "environ", "[", "\"HTTP_HOST\"", "]", "if", "environ", "[", "\"wsgi.url_scheme\"", "]", "==", "\"http\"", "a...
Return the host for the given WSGI environment. Yanked from Werkzeug.
[ "Return", "the", "host", "for", "the", "given", "WSGI", "environment", ".", "Yanked", "from", "Werkzeug", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L35-L55
234,215
getsentry/sentry-python
sentry_sdk/integrations/wsgi.py
get_request_url
def get_request_url(environ): # type: (Dict[str, str]) -> str """Return the absolute URL without query string for the given WSGI environment.""" return "%s://%s/%s" % ( environ.get("wsgi.url_scheme"), get_host(environ), wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("/"), )
python
def get_request_url(environ): # type: (Dict[str, str]) -> str return "%s://%s/%s" % ( environ.get("wsgi.url_scheme"), get_host(environ), wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("/"), )
[ "def", "get_request_url", "(", "environ", ")", ":", "# type: (Dict[str, str]) -> str", "return", "\"%s://%s/%s\"", "%", "(", "environ", ".", "get", "(", "\"wsgi.url_scheme\"", ")", ",", "get_host", "(", "environ", ")", ",", "wsgi_decoding_dance", "(", "environ", "...
Return the absolute URL without query string for the given WSGI environment.
[ "Return", "the", "absolute", "URL", "without", "query", "string", "for", "the", "given", "WSGI", "environment", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L58-L66
234,216
getsentry/sentry-python
sentry_sdk/integrations/wsgi.py
_get_environ
def _get_environ(environ): # type: (Dict[str, str]) -> Iterator[Tuple[str, str]] """ Returns our whitelisted environment variables. """ keys = ["SERVER_NAME", "SERVER_PORT"] if _should_send_default_pii(): # Add all three headers here to make debugging of proxy setup easier. keys += ["REMOTE_ADDR", "HTTP_X_FORWARDED_FOR", "HTTP_X_REAL_IP"] for key in keys: if key in environ: yield key, environ[key]
python
def _get_environ(environ): # type: (Dict[str, str]) -> Iterator[Tuple[str, str]] keys = ["SERVER_NAME", "SERVER_PORT"] if _should_send_default_pii(): # Add all three headers here to make debugging of proxy setup easier. keys += ["REMOTE_ADDR", "HTTP_X_FORWARDED_FOR", "HTTP_X_REAL_IP"] for key in keys: if key in environ: yield key, environ[key]
[ "def", "_get_environ", "(", "environ", ")", ":", "# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]", "keys", "=", "[", "\"SERVER_NAME\"", ",", "\"SERVER_PORT\"", "]", "if", "_should_send_default_pii", "(", ")", ":", "# Add all three headers here to make debugging of proxy ...
Returns our whitelisted environment variables.
[ "Returns", "our", "whitelisted", "environment", "variables", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L96-L108
234,217
getsentry/sentry-python
sentry_sdk/integrations/wsgi.py
get_client_ip
def get_client_ip(environ): # type: (Dict[str, str]) -> Optional[Any] """ Infer the user IP address from various headers. This cannot be used in security sensitive situations since the value may be forged from a client, but it's good enough for the event payload. """ try: return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip() except (KeyError, IndexError): pass try: return environ["HTTP_X_REAL_IP"] except KeyError: pass return environ.get("REMOTE_ADDR")
python
def get_client_ip(environ): # type: (Dict[str, str]) -> Optional[Any] try: return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip() except (KeyError, IndexError): pass try: return environ["HTTP_X_REAL_IP"] except KeyError: pass return environ.get("REMOTE_ADDR")
[ "def", "get_client_ip", "(", "environ", ")", ":", "# type: (Dict[str, str]) -> Optional[Any]", "try", ":", "return", "environ", "[", "\"HTTP_X_FORWARDED_FOR\"", "]", ".", "split", "(", "\",\"", ")", "[", "0", "]", ".", "strip", "(", ")", "except", "(", "KeyErr...
Infer the user IP address from various headers. This cannot be used in security sensitive situations since the value may be forged from a client, but it's good enough for the event payload.
[ "Infer", "the", "user", "IP", "address", "from", "various", "headers", ".", "This", "cannot", "be", "used", "in", "security", "sensitive", "situations", "since", "the", "value", "may", "be", "forged", "from", "a", "client", "but", "it", "s", "good", "enoug...
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/integrations/wsgi.py#L132-L149
234,218
getsentry/sentry-python
sentry_sdk/utils.py
event_hint_with_exc_info
def event_hint_with_exc_info(exc_info=None): # type: (ExcInfo) -> Dict[str, Optional[ExcInfo]] """Creates a hint with the exc info filled in.""" if exc_info is None: exc_info = sys.exc_info() else: exc_info = exc_info_from_error(exc_info) if exc_info[0] is None: exc_info = None return {"exc_info": exc_info}
python
def event_hint_with_exc_info(exc_info=None): # type: (ExcInfo) -> Dict[str, Optional[ExcInfo]] if exc_info is None: exc_info = sys.exc_info() else: exc_info = exc_info_from_error(exc_info) if exc_info[0] is None: exc_info = None return {"exc_info": exc_info}
[ "def", "event_hint_with_exc_info", "(", "exc_info", "=", "None", ")", ":", "# type: (ExcInfo) -> Dict[str, Optional[ExcInfo]]", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "else", ":", "exc_info", "=", "exc_info_from_error...
Creates a hint with the exc info filled in.
[ "Creates", "a", "hint", "with", "the", "exc", "info", "filled", "in", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L81-L90
234,219
getsentry/sentry-python
sentry_sdk/utils.py
format_and_strip
def format_and_strip(template, params, strip_string=strip_string): """Format a string containing %s for placeholders and call `strip_string` on each parameter. The string template itself does not have a maximum length. TODO: handle other placeholders, not just %s """ chunks = template.split(u"%s") if not chunks: raise ValueError("No formatting placeholders found") params = list(reversed(params)) rv_remarks = [] rv_original_length = 0 rv_length = 0 rv = [] def realign_remark(remark): return [ (rv_length + x if isinstance(x, int_types) and i < 4 else x) for i, x in enumerate(remark) ] for chunk in chunks[:-1]: rv.append(chunk) rv_length += len(chunk) rv_original_length += len(chunk) if not params: raise ValueError("Not enough params.") param = params.pop() stripped_param = strip_string(param) if isinstance(stripped_param, AnnotatedValue): rv_remarks.extend( realign_remark(remark) for remark in stripped_param.metadata["rem"] ) stripped_param = stripped_param.value rv_original_length += len(param) rv_length += len(stripped_param) rv.append(stripped_param) rv.append(chunks[-1]) rv_length += len(chunks[-1]) rv_original_length += len(chunks[-1]) rv = u"".join(rv) assert len(rv) == rv_length if not rv_remarks: return rv return AnnotatedValue( value=rv, metadata={"len": rv_original_length, "rem": rv_remarks} )
python
def format_and_strip(template, params, strip_string=strip_string): chunks = template.split(u"%s") if not chunks: raise ValueError("No formatting placeholders found") params = list(reversed(params)) rv_remarks = [] rv_original_length = 0 rv_length = 0 rv = [] def realign_remark(remark): return [ (rv_length + x if isinstance(x, int_types) and i < 4 else x) for i, x in enumerate(remark) ] for chunk in chunks[:-1]: rv.append(chunk) rv_length += len(chunk) rv_original_length += len(chunk) if not params: raise ValueError("Not enough params.") param = params.pop() stripped_param = strip_string(param) if isinstance(stripped_param, AnnotatedValue): rv_remarks.extend( realign_remark(remark) for remark in stripped_param.metadata["rem"] ) stripped_param = stripped_param.value rv_original_length += len(param) rv_length += len(stripped_param) rv.append(stripped_param) rv.append(chunks[-1]) rv_length += len(chunks[-1]) rv_original_length += len(chunks[-1]) rv = u"".join(rv) assert len(rv) == rv_length if not rv_remarks: return rv return AnnotatedValue( value=rv, metadata={"len": rv_original_length, "rem": rv_remarks} )
[ "def", "format_and_strip", "(", "template", ",", "params", ",", "strip_string", "=", "strip_string", ")", ":", "chunks", "=", "template", ".", "split", "(", "u\"%s\"", ")", "if", "not", "chunks", ":", "raise", "ValueError", "(", "\"No formatting placeholders fou...
Format a string containing %s for placeholders and call `strip_string` on each parameter. The string template itself does not have a maximum length. TODO: handle other placeholders, not just %s
[ "Format", "a", "string", "containing", "%s", "for", "placeholders", "and", "call", "strip_string", "on", "each", "parameter", ".", "The", "string", "template", "itself", "does", "not", "have", "a", "maximum", "length", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L876-L930
234,220
getsentry/sentry-python
sentry_sdk/utils.py
Auth.store_api_url
def store_api_url(self): """Returns the API url for storing events.""" return "%s://%s%sapi/%s/store/" % ( self.scheme, self.host, self.path, self.project_id, )
python
def store_api_url(self): return "%s://%s%sapi/%s/store/" % ( self.scheme, self.host, self.path, self.project_id, )
[ "def", "store_api_url", "(", "self", ")", ":", "return", "\"%s://%s%sapi/%s/store/\"", "%", "(", "self", ".", "scheme", ",", "self", ".", "host", ",", "self", ".", "path", ",", "self", ".", "project_id", ",", ")" ]
Returns the API url for storing events.
[ "Returns", "the", "API", "url", "for", "storing", "events", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L182-L189
234,221
getsentry/sentry-python
sentry_sdk/utils.py
Auth.to_header
def to_header(self, timestamp=None): """Returns the auth header a string.""" rv = [("sentry_key", self.public_key), ("sentry_version", self.version)] if timestamp is not None: rv.append(("sentry_timestamp", str(to_timestamp(timestamp)))) if self.client is not None: rv.append(("sentry_client", self.client)) if self.secret_key is not None: rv.append(("sentry_secret", self.secret_key)) return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv)
python
def to_header(self, timestamp=None): rv = [("sentry_key", self.public_key), ("sentry_version", self.version)] if timestamp is not None: rv.append(("sentry_timestamp", str(to_timestamp(timestamp)))) if self.client is not None: rv.append(("sentry_client", self.client)) if self.secret_key is not None: rv.append(("sentry_secret", self.secret_key)) return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv)
[ "def", "to_header", "(", "self", ",", "timestamp", "=", "None", ")", ":", "rv", "=", "[", "(", "\"sentry_key\"", ",", "self", ".", "public_key", ")", ",", "(", "\"sentry_version\"", ",", "self", ".", "version", ")", "]", "if", "timestamp", "is", "not",...
Returns the auth header a string.
[ "Returns", "the", "auth", "header", "a", "string", "." ]
a1d77722bdce0b94660ebf50b5c4a4645916d084
https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/utils.py#L191-L200
234,222
abseil/abseil-py
absl/flags/_defines.py
_register_bounds_validator_if_needed
def _register_bounds_validator_if_needed(parser, name, flag_values): """Enforces lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser), provides lower and upper bounds, and help text to display. name: str, name of the flag flag_values: FlagValues. """ if parser.lower_bound is not None or parser.upper_bound is not None: def checker(value): if value is not None and parser.is_outside_bounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise _exceptions.ValidationError(message) return True _validators.register_validator(name, checker, flag_values=flag_values)
python
def _register_bounds_validator_if_needed(parser, name, flag_values): if parser.lower_bound is not None or parser.upper_bound is not None: def checker(value): if value is not None and parser.is_outside_bounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise _exceptions.ValidationError(message) return True _validators.register_validator(name, checker, flag_values=flag_values)
[ "def", "_register_bounds_validator_if_needed", "(", "parser", ",", "name", ",", "flag_values", ")", ":", "if", "parser", ".", "lower_bound", "is", "not", "None", "or", "parser", ".", "upper_bound", "is", "not", "None", ":", "def", "checker", "(", "value", ")...
Enforces lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser), provides lower and upper bounds, and help text to display. name: str, name of the flag flag_values: FlagValues.
[ "Enforces", "lower", "and", "upper", "bounds", "for", "numeric", "flags", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L39-L56
234,223
abseil/abseil-py
absl/flags/_defines.py
DEFINE
def DEFINE(parser, name, default, help, flag_values=_flagvalues.FLAGS, # pylint: disable=redefined-builtin,invalid-name serializer=None, module_name=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser, used to parse the flag arguments. name: str, the flag name. default: The default value of the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. serializer: ArgumentSerializer, the flag serializer instance. module_name: str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: dict, the extra keyword args that are passed to Flag __init__. """ DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args), flag_values, module_name)
python
def DEFINE(parser, name, default, help, flag_values=_flagvalues.FLAGS, # pylint: disable=redefined-builtin,invalid-name serializer=None, module_name=None, **args): DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args), flag_values, module_name)
[ "def", "DEFINE", "(", "parser", ",", "name", ",", "default", ",", "help", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "# pylint: disable=redefined-builtin,invalid-name", "serializer", "=", "None", ",", "module_name", "=", "None", ",", "*", "*", ...
Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser, used to parse the flag arguments. name: str, the flag name. default: The default value of the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. serializer: ArgumentSerializer, the flag serializer instance. module_name: str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: dict, the extra keyword args that are passed to Flag __init__.
[ "Registers", "a", "generic", "Flag", "object", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L59-L82
234,224
abseil/abseil-py
absl/flags/_defines.py
DEFINE_string
def DEFINE_string( # pylint: disable=invalid-name,redefined-builtin name, default, help, flag_values=_flagvalues.FLAGS, **args): """Registers a flag whose value can be any string.""" parser = _argument_parser.ArgumentParser() serializer = _argument_parser.ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args)
python
def DEFINE_string( # pylint: disable=invalid-name,redefined-builtin name, default, help, flag_values=_flagvalues.FLAGS, **args): parser = _argument_parser.ArgumentParser() serializer = _argument_parser.ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args)
[ "def", "DEFINE_string", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "*", "*", "args", ")", ":", "parser", "=", "_argument_parser", ".", "ArgumentParser", "...
Registers a flag whose value can be any string.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "any", "string", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L236-L241
234,225
abseil/abseil-py
absl/flags/_defines.py
DEFINE_boolean
def DEFINE_boolean( # pylint: disable=invalid-name,redefined-builtin name, default, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. Args: name: str, the flag name. default: bool|str|None, the default value of the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. module_name: str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: dict, the extra keyword args that are passed to Flag __init__. """ DEFINE_flag(_flag.BooleanFlag(name, default, help, **args), flag_values, module_name)
python
def DEFINE_boolean( # pylint: disable=invalid-name,redefined-builtin name, default, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): DEFINE_flag(_flag.BooleanFlag(name, default, help, **args), flag_values, module_name)
[ "def", "DEFINE_boolean", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "module_name", "=", "None", ",", "*", "*", "args", ")", ":", "DEFINE_flag", "(", "_f...
Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. Args: name: str, the flag name. default: bool|str|None, the default value of the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. module_name: str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: dict, the extra keyword args that are passed to Flag __init__.
[ "Registers", "a", "boolean", "flag", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L244-L268
234,226
abseil/abseil-py
absl/flags/_defines.py
DEFINE_float
def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=_flagvalues.FLAGS, **args): # pylint: disable=invalid-name """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. Args: name: str, the flag name. default: float|str|None, the default value of the flag. help: str, the help message. lower_bound: float, min value of the flag. upper_bound: float, max value of the flag. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args: dict, the extra keyword args that are passed to DEFINE. """ parser = _argument_parser.FloatParser(lower_bound, upper_bound) serializer = _argument_parser.ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
python
def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=_flagvalues.FLAGS, **args): # pylint: disable=invalid-name parser = _argument_parser.FloatParser(lower_bound, upper_bound) serializer = _argument_parser.ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
[ "def", "DEFINE_float", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "*", "*", "args", ")...
Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. Args: name: str, the flag name. default: float|str|None, the default value of the flag. help: str, the help message. lower_bound: float, min value of the flag. upper_bound: float, max value of the flag. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args: dict, the extra keyword args that are passed to DEFINE.
[ "Registers", "a", "flag", "whose", "value", "must", "be", "a", "float", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L271-L292
234,227
abseil/abseil-py
absl/flags/_defines.py
DEFINE_integer
def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=_flagvalues.FLAGS, **args): """Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. Args: name: str, the flag name. default: int|str|None, the default value of the flag. help: str, the help message. lower_bound: int, min value of the flag. upper_bound: int, max value of the flag. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args: dict, the extra keyword args that are passed to DEFINE. """ parser = _argument_parser.IntegerParser(lower_bound, upper_bound) serializer = _argument_parser.ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
python
def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=_flagvalues.FLAGS, **args): parser = _argument_parser.IntegerParser(lower_bound, upper_bound) serializer = _argument_parser.ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
[ "def", "DEFINE_integer", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "*", "*", "args", ...
Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. Args: name: str, the flag name. default: int|str|None, the default value of the flag. help: str, the help message. lower_bound: int, min value of the flag. upper_bound: int, max value of the flag. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args: dict, the extra keyword args that are passed to DEFINE.
[ "Registers", "a", "flag", "whose", "value", "must", "be", "an", "integer", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L295-L316
234,228
abseil/abseil-py
absl/flags/_defines.py
DEFINE_enum_class
def DEFINE_enum_class( # pylint: disable=invalid-name,redefined-builtin name, default, enum_class, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): """Registers a flag whose value can be the name of enum members. Args: name: str, the flag name. default: Enum|str|None, the default value of the flag. enum_class: class, the Enum class with all the possible values for the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. module_name: str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: dict, the extra keyword args that are passed to Flag __init__. """ DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args), flag_values, module_name)
python
def DEFINE_enum_class( # pylint: disable=invalid-name,redefined-builtin name, default, enum_class, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args), flag_values, module_name)
[ "def", "DEFINE_enum_class", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "enum_class", ",", "help", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "module_name", "=", "None", ",", "*", "*", "args", ")", ":", "...
Registers a flag whose value can be the name of enum members. Args: name: str, the flag name. default: Enum|str|None, the default value of the flag. enum_class: class, the Enum class with all the possible values for the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. module_name: str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: dict, the extra keyword args that are passed to Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "the", "name", "of", "enum", "members", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L343-L360
234,229
abseil/abseil-py
absl/flags/_defines.py
DEFINE_spaceseplist
def DEFINE_spaceseplist( # pylint: disable=invalid-name,redefined-builtin name, default, help, comma_compat=False, flag_values=_flagvalues.FLAGS, **args): """Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. Args: name: str, the flag name. default: list|str|None, the default value of the flag. help: str, the help message. comma_compat: bool - Whether to support comma as an additional separator. If false then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ parser = _argument_parser.WhitespaceSeparatedListParser( comma_compat=comma_compat) serializer = _argument_parser.ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args)
python
def DEFINE_spaceseplist( # pylint: disable=invalid-name,redefined-builtin name, default, help, comma_compat=False, flag_values=_flagvalues.FLAGS, **args): parser = _argument_parser.WhitespaceSeparatedListParser( comma_compat=comma_compat) serializer = _argument_parser.ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args)
[ "def", "DEFINE_spaceseplist", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "comma_compat", "=", "False", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "*", "*", "args", ")", ":", "parser", "=", "...
Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. Args: name: str, the flag name. default: list|str|None, the default value of the flag. help: str, the help message. comma_compat: bool - Whether to support comma as an additional separator. If false then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "is", "a", "whitespace", "-", "separated", "list", "of", "strings", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L383-L405
234,230
abseil/abseil-py
absl/flags/_defines.py
DEFINE_multi_enum
def DEFINE_multi_enum( # pylint: disable=invalid-name,redefined-builtin name, default, enum_values, help, flag_values=_flagvalues.FLAGS, case_sensitive=True, **args): """Registers a flag whose value can be a list strings from enum_values. Use the flag on the command line multiple times to place multiple enum values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. Args: name: str, the flag name. default: Union[Iterable[Text], Text, None], the default value of the flag; see `DEFINE_multi`. enum_values: [str], a non-empty list of strings with the possible values for the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. case_sensitive: Whether or not the enum is to be case-sensitive. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ parser = _argument_parser.EnumParser(enum_values, case_sensitive) serializer = _argument_parser.ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
python
def DEFINE_multi_enum( # pylint: disable=invalid-name,redefined-builtin name, default, enum_values, help, flag_values=_flagvalues.FLAGS, case_sensitive=True, **args): parser = _argument_parser.EnumParser(enum_values, case_sensitive) serializer = _argument_parser.ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
[ "def", "DEFINE_multi_enum", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "enum_values", ",", "help", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "case_sensitive", "=", "True", ",", "*", "*", "args", ")", ":",...
Registers a flag whose value can be a list strings from enum_values. Use the flag on the command line multiple times to place multiple enum values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. Args: name: str, the flag name. default: Union[Iterable[Text], Text, None], the default value of the flag; see `DEFINE_multi`. enum_values: [str], a non-empty list of strings with the possible values for the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. case_sensitive: Whether or not the enum is to be case-sensitive. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "a", "list", "strings", "from", "enum_values", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L519-L544
234,231
abseil/abseil-py
absl/flags/_defines.py
DEFINE_multi_enum_class
def DEFINE_multi_enum_class( # pylint: disable=invalid-name,redefined-builtin name, default, enum_class, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): """Registers a flag whose value can be a list of enum members. Use the flag on the command line multiple times to place multiple enum values into the list. Args: name: str, the flag name. default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the default value of the flag; see `DEFINE_multi`; only differences are documented here. If the value is a single Enum, it is treated as a single-item list of that Enum value. If it is an iterable, text values within the iterable will be converted to the equivalent Enum objects. enum_class: class, the Enum class with all the possible values for the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. module_name: A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ DEFINE_flag( _flag.MultiEnumClassFlag(name, default, help, enum_class), flag_values, module_name, **args)
python
def DEFINE_multi_enum_class( # pylint: disable=invalid-name,redefined-builtin name, default, enum_class, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): DEFINE_flag( _flag.MultiEnumClassFlag(name, default, help, enum_class), flag_values, module_name, **args)
[ "def", "DEFINE_multi_enum_class", "(", "# pylint: disable=invalid-name,redefined-builtin", "name", ",", "default", ",", "enum_class", ",", "help", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "module_name", "=", "None", ",", "*", "*", "args", ")", ":...
Registers a flag whose value can be a list of enum members. Use the flag on the command line multiple times to place multiple enum values into the list. Args: name: str, the flag name. default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the default value of the flag; see `DEFINE_multi`; only differences are documented here. If the value is a single Enum, it is treated as a single-item list of that Enum value. If it is an iterable, text values within the iterable will be converted to the equivalent Enum objects. enum_class: class, the Enum class with all the possible values for the flag. help: str, the help message. flag_values: FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. module_name: A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "a", "list", "of", "enum", "members", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L547-L579
234,232
abseil/abseil-py
absl/flags/_argument_parser.py
ArgumentParser.parse
def parse(self, argument): """Parses the string argument and returns the native value. By default it returns its argument unmodified. Args: argument: string argument passed in the commandline. Raises: ValueError: Raised when it fails to parse the argument. TypeError: Raised when the argument has the wrong type. Returns: The parsed value in native type. """ if not isinstance(argument, six.string_types): raise TypeError('flag value must be a string, found "{}"'.format( type(argument))) return argument
python
def parse(self, argument): if not isinstance(argument, six.string_types): raise TypeError('flag value must be a string, found "{}"'.format( type(argument))) return argument
[ "def", "parse", "(", "self", ",", "argument", ")", ":", "if", "not", "isinstance", "(", "argument", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'flag value must be a string, found \"{}\"'", ".", "format", "(", "type", "(", "argument"...
Parses the string argument and returns the native value. By default it returns its argument unmodified. Args: argument: string argument passed in the commandline. Raises: ValueError: Raised when it fails to parse the argument. TypeError: Raised when the argument has the wrong type. Returns: The parsed value in native type.
[ "Parses", "the", "string", "argument", "and", "returns", "the", "native", "value", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L97-L115
234,233
abseil/abseil-py
absl/flags/_argument_parser.py
NumericParser.is_outside_bounds
def is_outside_bounds(self, val): """Returns whether the value is outside the bounds or not.""" return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound))
python
def is_outside_bounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound))
[ "def", "is_outside_bounds", "(", "self", ",", "val", ")", ":", "return", "(", "(", "self", ".", "lower_bound", "is", "not", "None", "and", "val", "<", "self", ".", "lower_bound", ")", "or", "(", "self", ".", "upper_bound", "is", "not", "None", "and", ...
Returns whether the value is outside the bounds or not.
[ "Returns", "whether", "the", "value", "is", "outside", "the", "bounds", "or", "not", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L145-L148
234,234
abseil/abseil-py
absl/flags/_argument_parser.py
FloatParser.convert
def convert(self, argument): """Returns the float value of argument.""" if (_is_integer_type(argument) or isinstance(argument, float) or isinstance(argument, six.string_types)): return float(argument) else: raise TypeError( 'Expect argument to be a string, int, or float, found {}'.format( type(argument)))
python
def convert(self, argument): if (_is_integer_type(argument) or isinstance(argument, float) or isinstance(argument, six.string_types)): return float(argument) else: raise TypeError( 'Expect argument to be a string, int, or float, found {}'.format( type(argument)))
[ "def", "convert", "(", "self", ",", "argument", ")", ":", "if", "(", "_is_integer_type", "(", "argument", ")", "or", "isinstance", "(", "argument", ",", "float", ")", "or", "isinstance", "(", "argument", ",", "six", ".", "string_types", ")", ")", ":", ...
Returns the float value of argument.
[ "Returns", "the", "float", "value", "of", "argument", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L209-L217
234,235
abseil/abseil-py
absl/flags/_argument_parser.py
IntegerParser.convert
def convert(self, argument): """Returns the int value of argument.""" if _is_integer_type(argument): return argument elif isinstance(argument, six.string_types): base = 10 if len(argument) > 2 and argument[0] == '0': if argument[1] == 'o': base = 8 elif argument[1] == 'x': base = 16 return int(argument, base) else: raise TypeError('Expect argument to be a string or int, found {}'.format( type(argument)))
python
def convert(self, argument): if _is_integer_type(argument): return argument elif isinstance(argument, six.string_types): base = 10 if len(argument) > 2 and argument[0] == '0': if argument[1] == 'o': base = 8 elif argument[1] == 'x': base = 16 return int(argument, base) else: raise TypeError('Expect argument to be a string or int, found {}'.format( type(argument)))
[ "def", "convert", "(", "self", ",", "argument", ")", ":", "if", "_is_integer_type", "(", "argument", ")", ":", "return", "argument", "elif", "isinstance", "(", "argument", ",", "six", ".", "string_types", ")", ":", "base", "=", "10", "if", "len", "(", ...
Returns the int value of argument.
[ "Returns", "the", "int", "value", "of", "argument", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L254-L268
234,236
abseil/abseil-py
absl/flags/_argument_parser.py
EnumClassParser.parse
def parse(self, argument): """Determines validity of argument and returns the correct element of enum. Args: argument: str or Enum class member, the supplied flag value. Returns: The first matching Enum class member in Enum class. Raises: ValueError: Raised when argument didn't match anything in enum. """ if isinstance(argument, self.enum_class): return argument if argument not in self.enum_class.__members__: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_class.__members__.keys())) else: return self.enum_class[argument]
python
def parse(self, argument): if isinstance(argument, self.enum_class): return argument if argument not in self.enum_class.__members__: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_class.__members__.keys())) else: return self.enum_class[argument]
[ "def", "parse", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "self", ".", "enum_class", ")", ":", "return", "argument", "if", "argument", "not", "in", "self", ".", "enum_class", ".", "__members__", ":", "raise", "Valu...
Determines validity of argument and returns the correct element of enum. Args: argument: str or Enum class member, the supplied flag value. Returns: The first matching Enum class member in Enum class. Raises: ValueError: Raised when argument didn't match anything in enum.
[ "Determines", "validity", "of", "argument", "and", "returns", "the", "correct", "element", "of", "enum", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L380-L398
234,237
abseil/abseil-py
absl/flags/_argument_parser.py
ListParser.parse
def parse(self, argument): """Parses argument as comma-separated list of strings.""" if isinstance(argument, list): return argument elif not argument: return [] else: try: return [s.strip() for s in list(csv.reader([argument], strict=True))[0]] except csv.Error as e: # Provide a helpful report for case like # --listflag="$(printf 'hello,\nworld')" # IOW, list flag values containing naked newlines. This error # was previously "reported" by allowing csv.Error to # propagate. raise ValueError('Unable to parse the value %r as a %s: %s' % (argument, self.flag_type(), e))
python
def parse(self, argument): if isinstance(argument, list): return argument elif not argument: return [] else: try: return [s.strip() for s in list(csv.reader([argument], strict=True))[0]] except csv.Error as e: # Provide a helpful report for case like # --listflag="$(printf 'hello,\nworld')" # IOW, list flag values containing naked newlines. This error # was previously "reported" by allowing csv.Error to # propagate. raise ValueError('Unable to parse the value %r as a %s: %s' % (argument, self.flag_type(), e))
[ "def", "parse", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "list", ")", ":", "return", "argument", "elif", "not", "argument", ":", "return", "[", "]", "else", ":", "try", ":", "return", "[", "s", ".", "strip", ...
Parses argument as comma-separated list of strings.
[ "Parses", "argument", "as", "comma", "-", "separated", "list", "of", "strings", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L494-L510
234,238
abseil/abseil-py
absl/flags/_argument_parser.py
WhitespaceSeparatedListParser.parse
def parse(self, argument): """Parses argument as whitespace-separated list of strings. It also parses argument as comma-separated list of strings if requested. Args: argument: string argument passed in the commandline. Returns: [str], the parsed flag value. """ if isinstance(argument, list): return argument elif not argument: return [] else: if self._comma_compat: argument = argument.replace(',', ' ') return argument.split()
python
def parse(self, argument): if isinstance(argument, list): return argument elif not argument: return [] else: if self._comma_compat: argument = argument.replace(',', ' ') return argument.split()
[ "def", "parse", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "list", ")", ":", "return", "argument", "elif", "not", "argument", ":", "return", "[", "]", "else", ":", "if", "self", ".", "_comma_compat", ":", "argumen...
Parses argument as whitespace-separated list of strings. It also parses argument as comma-separated list of strings if requested. Args: argument: string argument passed in the commandline. Returns: [str], the parsed flag value.
[ "Parses", "argument", "as", "whitespace", "-", "separated", "list", "of", "strings", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L534-L552
234,239
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues.set_gnu_getopt
def set_gnu_getopt(self, gnu_getopt=True): """Sets whether or not to use GNU style scanning. GNU style allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: gnu_getopt: bool, whether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = gnu_getopt self.__dict__['__use_gnu_getopt_explicitly_set'] = True
python
def set_gnu_getopt(self, gnu_getopt=True): self.__dict__['__use_gnu_getopt'] = gnu_getopt self.__dict__['__use_gnu_getopt_explicitly_set'] = True
[ "def", "set_gnu_getopt", "(", "self", ",", "gnu_getopt", "=", "True", ")", ":", "self", ".", "__dict__", "[", "'__use_gnu_getopt'", "]", "=", "gnu_getopt", "self", ".", "__dict__", "[", "'__use_gnu_getopt_explicitly_set'", "]", "=", "True" ]
Sets whether or not to use GNU style scanning. GNU style allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: gnu_getopt: bool, whether or not to use GNU style scanning.
[ "Sets", "whether", "or", "not", "to", "use", "GNU", "style", "scanning", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L126-L136
234,240
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues._assert_validators
def _assert_validators(self, validators): """Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueError: Raised if validation fails for at least one validator. """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.verify(self) except _exceptions.ValidationError as e: message = validator.print_flags_with_values(self) raise _exceptions.IllegalFlagValueError('%s: %s' % (message, str(e)))
python
def _assert_validators(self, validators): for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.verify(self) except _exceptions.ValidationError as e: message = validator.print_flags_with_values(self) raise _exceptions.IllegalFlagValueError('%s: %s' % (message, str(e)))
[ "def", "_assert_validators", "(", "self", ",", "validators", ")", ":", "for", "validator", "in", "sorted", "(", "validators", ",", "key", "=", "lambda", "validator", ":", "validator", ".", "insertion_index", ")", ":", "try", ":", "validator", ".", "verify", ...
Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueError: Raised if validation fails for at least one validator.
[ "Asserts", "if", "all", "validators", "in", "the", "list", "are", "satisfied", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L512-L531
234,241
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues.set_default
def set_default(self, name, value): """Changes the default value of the named flag object. The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value. Args: name: str, the name of the flag to modify. value: The new default value. Raises: UnrecognizedFlagError: Raised when there is no registered flag named name. IllegalFlagValueError: Raised when value is not valid. """ fl = self._flags() if name not in fl: self._set_unknown_flag(name, value) return fl[name]._set_default(value) # pylint: disable=protected-access self._assert_validators(fl[name].validators)
python
def set_default(self, name, value): fl = self._flags() if name not in fl: self._set_unknown_flag(name, value) return fl[name]._set_default(value) # pylint: disable=protected-access self._assert_validators(fl[name].validators)
[ "def", "set_default", "(", "self", ",", "name", ",", "value", ")", ":", "fl", "=", "self", ".", "_flags", "(", ")", "if", "name", "not", "in", "fl", ":", "self", ".", "_set_unknown_flag", "(", "name", ",", "value", ")", "return", "fl", "[", "name",...
Changes the default value of the named flag object. The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value. Args: name: str, the name of the flag to modify. value: The new default value. Raises: UnrecognizedFlagError: Raised when there is no registered flag named name. IllegalFlagValueError: Raised when value is not valid.
[ "Changes", "the", "default", "value", "of", "the", "named", "flag", "object", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L563-L583
234,242
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues.flag_values_dict
def flag_values_dict(self): """Returns a dictionary that maps flag names to flag values.""" return {name: flag.value for name, flag in six.iteritems(self._flags())}
python
def flag_values_dict(self): return {name: flag.value for name, flag in six.iteritems(self._flags())}
[ "def", "flag_values_dict", "(", "self", ")", ":", "return", "{", "name", ":", "flag", ".", "value", "for", "name", ",", "flag", "in", "six", ".", "iteritems", "(", "self", ".", "_flags", "(", ")", ")", "}" ]
Returns a dictionary that maps flag names to flag values.
[ "Returns", "a", "dictionary", "that", "maps", "flag", "names", "to", "flag", "values", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L821-L823
234,243
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues.get_help
def get_help(self, prefix='', include_special_flags=True): """Returns a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message. """ flags_by_module = self.flags_by_module_dict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = sys.argv[0] if main_module in modules: modules.remove(main_module) modules = [main_module] + modules return self._get_help_for_modules(modules, prefix, include_special_flags) else: output_lines = [] # Just print one long list of flags. values = six.itervalues(self._flags()) if include_special_flags: values = itertools.chain( values, six.itervalues(_helpers.SPECIAL_FLAGS._flags())) # pylint: disable=protected-access self._render_flag_list(values, output_lines, prefix) return '\n'.join(output_lines)
python
def get_help(self, prefix='', include_special_flags=True): flags_by_module = self.flags_by_module_dict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = sys.argv[0] if main_module in modules: modules.remove(main_module) modules = [main_module] + modules return self._get_help_for_modules(modules, prefix, include_special_flags) else: output_lines = [] # Just print one long list of flags. values = six.itervalues(self._flags()) if include_special_flags: values = itertools.chain( values, six.itervalues(_helpers.SPECIAL_FLAGS._flags())) # pylint: disable=protected-access self._render_flag_list(values, output_lines, prefix) return '\n'.join(output_lines)
[ "def", "get_help", "(", "self", ",", "prefix", "=", "''", ",", "include_special_flags", "=", "True", ")", ":", "flags_by_module", "=", "self", ".", "flags_by_module_dict", "(", ")", "if", "flags_by_module", ":", "modules", "=", "sorted", "(", "flags_by_module"...
Returns a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message.
[ "Returns", "a", "help", "string", "for", "all", "known", "flags", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L829-L857
234,244
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues._get_help_for_modules
def _get_help_for_modules(self, modules, prefix, include_special_flags): """Returns the help string for a list of modules. Private to absl.flags package. Args: modules: List[str], a list of modules to get the help string for. prefix: str, a string that is prepended to each generated help line. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. """ output_lines = [] for module in modules: self._render_our_module_flags(module, output_lines, prefix) if include_special_flags: self._render_module_flags( 'absl.flags', six.itervalues(_helpers.SPECIAL_FLAGS._flags()), # pylint: disable=protected-access output_lines, prefix) return '\n'.join(output_lines)
python
def _get_help_for_modules(self, modules, prefix, include_special_flags): output_lines = [] for module in modules: self._render_our_module_flags(module, output_lines, prefix) if include_special_flags: self._render_module_flags( 'absl.flags', six.itervalues(_helpers.SPECIAL_FLAGS._flags()), # pylint: disable=protected-access output_lines, prefix) return '\n'.join(output_lines)
[ "def", "_get_help_for_modules", "(", "self", ",", "modules", ",", "prefix", ",", "include_special_flags", ")", ":", "output_lines", "=", "[", "]", "for", "module", "in", "modules", ":", "self", ".", "_render_our_module_flags", "(", "module", ",", "output_lines",...
Returns the help string for a list of modules. Private to absl.flags package. Args: modules: List[str], a list of modules to get the help string for. prefix: str, a string that is prepended to each generated help line. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok.
[ "Returns", "the", "help", "string", "for", "a", "list", "of", "modules", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L859-L879
234,245
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues._render_our_module_key_flags
def _render_our_module_key_flags(self, module, output_lines, prefix=''): """Returns a help string for the key flags of a given module. Args: module: module|str, the module to render key flags for. output_lines: [str], a list of strings. The generated help message lines will be appended to this list. prefix: str, a string that is prepended to each generated help line. """ key_flags = self.get_key_flags_for_module(module) if key_flags: self._render_module_flags(module, key_flags, output_lines, prefix)
python
def _render_our_module_key_flags(self, module, output_lines, prefix=''): key_flags = self.get_key_flags_for_module(module) if key_flags: self._render_module_flags(module, key_flags, output_lines, prefix)
[ "def", "_render_our_module_key_flags", "(", "self", ",", "module", ",", "output_lines", ",", "prefix", "=", "''", ")", ":", "key_flags", "=", "self", ".", "get_key_flags_for_module", "(", "module", ")", "if", "key_flags", ":", "self", ".", "_render_module_flags"...
Returns a help string for the key flags of a given module. Args: module: module|str, the module to render key flags for. output_lines: [str], a list of strings. The generated help message lines will be appended to this list. prefix: str, a string that is prepended to each generated help line.
[ "Returns", "a", "help", "string", "for", "the", "key", "flags", "of", "a", "given", "module", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L894-L905
234,246
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues.module_help
def module_help(self, module): """Describes the key flags of a module. Args: module: module|str, the module to describe the key flags for. Returns: str, describing the key flags of a module. """ helplist = [] self._render_our_module_key_flags(module, helplist) return '\n'.join(helplist)
python
def module_help(self, module): helplist = [] self._render_our_module_key_flags(module, helplist) return '\n'.join(helplist)
[ "def", "module_help", "(", "self", ",", "module", ")", ":", "helplist", "=", "[", "]", "self", ".", "_render_our_module_key_flags", "(", "module", ",", "helplist", ")", "return", "'\\n'", ".", "join", "(", "helplist", ")" ]
Describes the key flags of a module. Args: module: module|str, the module to describe the key flags for. Returns: str, describing the key flags of a module.
[ "Describes", "the", "key", "flags", "of", "a", "module", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L907-L918
234,247
abseil/abseil-py
absl/flags/_flagvalues.py
FlagValues.write_help_in_xml_format
def write_help_in_xml_format(self, outfile=None): """Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from https://github.com/gflags/gflags. We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. """ doc = minidom.Document() all_flag = doc.createElement('AllFlags') doc.appendChild(all_flag) all_flag.appendChild(_helpers.create_xml_dom_element( doc, 'program', os.path.basename(sys.argv[0]))) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) all_flag.appendChild(_helpers.create_xml_dom_element( doc, 'usage', usage_doc)) # Get list of key flags for the main module. key_flags = self.get_key_flags_for_module(sys.argv[0]) # Sort flags by declaring module name and next by flag name. flags_by_module = self.flags_by_module_dict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags all_flag.appendChild(flag._create_xml_dom_element( # pylint: disable=protected-access doc, module_name, is_key=is_key)) outfile = outfile or sys.stdout if six.PY2: outfile.write(doc.toprettyxml(indent=' ', encoding='utf-8')) else: outfile.write( doc.toprettyxml(indent=' ', encoding='utf-8').decode('utf-8')) outfile.flush()
python
def write_help_in_xml_format(self, outfile=None): doc = minidom.Document() all_flag = doc.createElement('AllFlags') doc.appendChild(all_flag) all_flag.appendChild(_helpers.create_xml_dom_element( doc, 'program', os.path.basename(sys.argv[0]))) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) all_flag.appendChild(_helpers.create_xml_dom_element( doc, 'usage', usage_doc)) # Get list of key flags for the main module. key_flags = self.get_key_flags_for_module(sys.argv[0]) # Sort flags by declaring module name and next by flag name. flags_by_module = self.flags_by_module_dict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags all_flag.appendChild(flag._create_xml_dom_element( # pylint: disable=protected-access doc, module_name, is_key=is_key)) outfile = outfile or sys.stdout if six.PY2: outfile.write(doc.toprettyxml(indent=' ', encoding='utf-8')) else: outfile.write( doc.toprettyxml(indent=' ', encoding='utf-8').decode('utf-8')) outfile.flush()
[ "def", "write_help_in_xml_format", "(", "self", ",", "outfile", "=", "None", ")", ":", "doc", "=", "minidom", ".", "Document", "(", ")", "all_flag", "=", "doc", ".", "createElement", "(", "'AllFlags'", ")", "doc", ".", "appendChild", "(", "all_flag", ")", ...
Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from https://github.com/gflags/gflags. We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout.
[ "Outputs", "flag", "documentation", "in", "XML", "format", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_flagvalues.py#L1206-L1255
234,248
abseil/abseil-py
absl/logging/converter.py
absl_to_cpp
def absl_to_cpp(level): """Converts an absl log level to a cpp log level. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in Abseil C++. """ if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level >= 0: # C++ log levels must be >= 0 return 0 else: return -level
python
def absl_to_cpp(level): if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level >= 0: # C++ log levels must be >= 0 return 0 else: return -level
[ "def", "absl_to_cpp", "(", "level", ")", ":", "if", "not", "isinstance", "(", "level", ",", "int", ")", ":", "raise", "TypeError", "(", "'Expect an int level, found {}'", ".", "format", "(", "type", "(", "level", ")", ")", ")", "if", "level", ">=", "0", ...
Converts an absl log level to a cpp log level. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in Abseil C++.
[ "Converts", "an", "absl", "log", "level", "to", "a", "cpp", "log", "level", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/converter.py#L117-L135
234,249
abseil/abseil-py
absl/logging/converter.py
absl_to_standard
def absl_to_standard(level): """Converts an integer level from the absl value to the standard value. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in standard logging. """ if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level < ABSL_FATAL: level = ABSL_FATAL if level <= ABSL_DEBUG: return ABSL_TO_STANDARD[level] # Maps to vlog levels. return STANDARD_DEBUG - level + 1
python
def absl_to_standard(level): if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level < ABSL_FATAL: level = ABSL_FATAL if level <= ABSL_DEBUG: return ABSL_TO_STANDARD[level] # Maps to vlog levels. return STANDARD_DEBUG - level + 1
[ "def", "absl_to_standard", "(", "level", ")", ":", "if", "not", "isinstance", "(", "level", ",", "int", ")", ":", "raise", "TypeError", "(", "'Expect an int level, found {}'", ".", "format", "(", "type", "(", "level", ")", ")", ")", "if", "level", "<", "...
Converts an integer level from the absl value to the standard value. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in standard logging.
[ "Converts", "an", "integer", "level", "from", "the", "absl", "value", "to", "the", "standard", "value", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/converter.py#L138-L157
234,250
abseil/abseil-py
absl/logging/converter.py
standard_to_absl
def standard_to_absl(level): """Converts an integer level from the standard value to the absl value. Args: level: int, a Python standard logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in absl logging. """ if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level < 0: level = 0 if level < STANDARD_DEBUG: # Maps to vlog levels. return STANDARD_DEBUG - level + 1 elif level < STANDARD_INFO: return ABSL_DEBUG elif level < STANDARD_WARNING: return ABSL_INFO elif level < STANDARD_ERROR: return ABSL_WARNING elif level < STANDARD_CRITICAL: return ABSL_ERROR else: return ABSL_FATAL
python
def standard_to_absl(level): if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level < 0: level = 0 if level < STANDARD_DEBUG: # Maps to vlog levels. return STANDARD_DEBUG - level + 1 elif level < STANDARD_INFO: return ABSL_DEBUG elif level < STANDARD_WARNING: return ABSL_INFO elif level < STANDARD_ERROR: return ABSL_WARNING elif level < STANDARD_CRITICAL: return ABSL_ERROR else: return ABSL_FATAL
[ "def", "standard_to_absl", "(", "level", ")", ":", "if", "not", "isinstance", "(", "level", ",", "int", ")", ":", "raise", "TypeError", "(", "'Expect an int level, found {}'", ".", "format", "(", "type", "(", "level", ")", ")", ")", "if", "level", "<", "...
Converts an integer level from the standard value to the absl value. Args: level: int, a Python standard logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in absl logging.
[ "Converts", "an", "integer", "level", "from", "the", "standard", "value", "to", "the", "absl", "value", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/converter.py#L172-L200
234,251
abseil/abseil-py
absl/app.py
parse_flags_with_usage
def parse_flags_with_usage(args): """Tries to parse the flags, print usage, and exit if unparseable. Args: args: [str], a non-empty list of the command line arguments including program name. Returns: [str], a non-empty list of remaining command line arguments after parsing flags, including program name. """ try: return FLAGS(args) except flags.Error as error: sys.stderr.write('FATAL Flags parsing error: %s\n' % error) sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n') sys.exit(1)
python
def parse_flags_with_usage(args): try: return FLAGS(args) except flags.Error as error: sys.stderr.write('FATAL Flags parsing error: %s\n' % error) sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n') sys.exit(1)
[ "def", "parse_flags_with_usage", "(", "args", ")", ":", "try", ":", "return", "FLAGS", "(", "args", ")", "except", "flags", ".", "Error", "as", "error", ":", "sys", ".", "stderr", ".", "write", "(", "'FATAL Flags parsing error: %s\\n'", "%", "error", ")", ...
Tries to parse the flags, print usage, and exit if unparseable. Args: args: [str], a non-empty list of the command line arguments including program name. Returns: [str], a non-empty list of remaining command line arguments after parsing flags, including program name.
[ "Tries", "to", "parse", "the", "flags", "print", "usage", "and", "exit", "if", "unparseable", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L147-L163
234,252
abseil/abseil-py
absl/app.py
define_help_flags
def define_help_flags(): """Registers help flags. Idempotent.""" # Use a global to ensure idempotence. global _define_help_flags_called if not _define_help_flags_called: flags.DEFINE_flag(HelpFlag()) flags.DEFINE_flag(HelpshortFlag()) # alias for --help flags.DEFINE_flag(HelpfullFlag()) flags.DEFINE_flag(HelpXMLFlag()) _define_help_flags_called = True
python
def define_help_flags(): # Use a global to ensure idempotence. global _define_help_flags_called if not _define_help_flags_called: flags.DEFINE_flag(HelpFlag()) flags.DEFINE_flag(HelpshortFlag()) # alias for --help flags.DEFINE_flag(HelpfullFlag()) flags.DEFINE_flag(HelpXMLFlag()) _define_help_flags_called = True
[ "def", "define_help_flags", "(", ")", ":", "# Use a global to ensure idempotence.", "global", "_define_help_flags_called", "if", "not", "_define_help_flags_called", ":", "flags", ".", "DEFINE_flag", "(", "HelpFlag", "(", ")", ")", "flags", ".", "DEFINE_flag", "(", "He...
Registers help flags. Idempotent.
[ "Registers", "help", "flags", ".", "Idempotent", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L169-L179
234,253
abseil/abseil-py
absl/app.py
_register_and_parse_flags_with_usage
def _register_and_parse_flags_with_usage( argv=None, flags_parser=parse_flags_with_usage, ): """Registers help flags, parses arguments and shows usage if appropriate. This also calls sys.exit(0) if flag --only_check_args is True. Args: argv: [str], a non-empty list of the command line arguments including program name, sys.argv is used if None. flags_parser: Callable[[List[Text]], Any], the function used to parse flags. The return value of this function is passed to `main` untouched. It must guarantee FLAGS is parsed after this function is called. Returns: The return value of `flags_parser`. When using the default `flags_parser`, it returns the following: [str], a non-empty list of remaining command line arguments after parsing flags, including program name. Raises: Error: Raised when flags_parser is called, but FLAGS is not parsed. SystemError: Raised when it's called more than once. """ if _register_and_parse_flags_with_usage.done: raise SystemError('Flag registration can be done only once.') define_help_flags() original_argv = sys.argv if argv is None else argv args_to_main = flags_parser(original_argv) if not FLAGS.is_parsed(): raise Error('FLAGS must be parsed after flags_parser is called.') # Exit when told so. if FLAGS.only_check_args: sys.exit(0) # Immediately after flags are parsed, bump verbosity to INFO if the flag has # not been set. if FLAGS['verbosity'].using_default_value: FLAGS.verbosity = 0 _register_and_parse_flags_with_usage.done = True return args_to_main
python
def _register_and_parse_flags_with_usage( argv=None, flags_parser=parse_flags_with_usage, ): if _register_and_parse_flags_with_usage.done: raise SystemError('Flag registration can be done only once.') define_help_flags() original_argv = sys.argv if argv is None else argv args_to_main = flags_parser(original_argv) if not FLAGS.is_parsed(): raise Error('FLAGS must be parsed after flags_parser is called.') # Exit when told so. if FLAGS.only_check_args: sys.exit(0) # Immediately after flags are parsed, bump verbosity to INFO if the flag has # not been set. if FLAGS['verbosity'].using_default_value: FLAGS.verbosity = 0 _register_and_parse_flags_with_usage.done = True return args_to_main
[ "def", "_register_and_parse_flags_with_usage", "(", "argv", "=", "None", ",", "flags_parser", "=", "parse_flags_with_usage", ",", ")", ":", "if", "_register_and_parse_flags_with_usage", ".", "done", ":", "raise", "SystemError", "(", "'Flag registration can be done only once...
Registers help flags, parses arguments and shows usage if appropriate. This also calls sys.exit(0) if flag --only_check_args is True. Args: argv: [str], a non-empty list of the command line arguments including program name, sys.argv is used if None. flags_parser: Callable[[List[Text]], Any], the function used to parse flags. The return value of this function is passed to `main` untouched. It must guarantee FLAGS is parsed after this function is called. Returns: The return value of `flags_parser`. When using the default `flags_parser`, it returns the following: [str], a non-empty list of remaining command line arguments after parsing flags, including program name. Raises: Error: Raised when flags_parser is called, but FLAGS is not parsed. SystemError: Raised when it's called more than once.
[ "Registers", "help", "flags", "parses", "arguments", "and", "shows", "usage", "if", "appropriate", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L182-L226
234,254
abseil/abseil-py
absl/app.py
_run_main
def _run_main(main, argv): """Calls main, optionally with pdb or profiler.""" if FLAGS.run_with_pdb: sys.exit(pdb.runcall(main, argv)) elif FLAGS.run_with_profiling or FLAGS.profile_file: # Avoid import overhead since most apps (including performance-sensitive # ones) won't be run with profiling. import atexit if FLAGS.use_cprofile_for_profiling: import cProfile as profile else: import profile profiler = profile.Profile() if FLAGS.profile_file: atexit.register(profiler.dump_stats, FLAGS.profile_file) else: atexit.register(profiler.print_stats) retval = profiler.runcall(main, argv) sys.exit(retval) else: sys.exit(main(argv))
python
def _run_main(main, argv): if FLAGS.run_with_pdb: sys.exit(pdb.runcall(main, argv)) elif FLAGS.run_with_profiling or FLAGS.profile_file: # Avoid import overhead since most apps (including performance-sensitive # ones) won't be run with profiling. import atexit if FLAGS.use_cprofile_for_profiling: import cProfile as profile else: import profile profiler = profile.Profile() if FLAGS.profile_file: atexit.register(profiler.dump_stats, FLAGS.profile_file) else: atexit.register(profiler.print_stats) retval = profiler.runcall(main, argv) sys.exit(retval) else: sys.exit(main(argv))
[ "def", "_run_main", "(", "main", ",", "argv", ")", ":", "if", "FLAGS", ".", "run_with_pdb", ":", "sys", ".", "exit", "(", "pdb", ".", "runcall", "(", "main", ",", "argv", ")", ")", "elif", "FLAGS", ".", "run_with_profiling", "or", "FLAGS", ".", "prof...
Calls main, optionally with pdb or profiler.
[ "Calls", "main", "optionally", "with", "pdb", "or", "profiler", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L231-L251
234,255
abseil/abseil-py
absl/app.py
_call_exception_handlers
def _call_exception_handlers(exception): """Calls any installed exception handlers.""" for handler in EXCEPTION_HANDLERS: try: if handler.wants(exception): handler.handle(exception) except: # pylint: disable=bare-except try: # We don't want to stop for exceptions in the exception handlers but # we shouldn't hide them either. logging.error(traceback.format_exc()) except: # pylint: disable=bare-except # In case even the logging statement fails, ignore. pass
python
def _call_exception_handlers(exception): for handler in EXCEPTION_HANDLERS: try: if handler.wants(exception): handler.handle(exception) except: # pylint: disable=bare-except try: # We don't want to stop for exceptions in the exception handlers but # we shouldn't hide them either. logging.error(traceback.format_exc()) except: # pylint: disable=bare-except # In case even the logging statement fails, ignore. pass
[ "def", "_call_exception_handlers", "(", "exception", ")", ":", "for", "handler", "in", "EXCEPTION_HANDLERS", ":", "try", ":", "if", "handler", ".", "wants", "(", "exception", ")", ":", "handler", ".", "handle", "(", "exception", ")", "except", ":", "# pylint...
Calls any installed exception handlers.
[ "Calls", "any", "installed", "exception", "handlers", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L254-L267
234,256
abseil/abseil-py
absl/app.py
run
def run( main, argv=None, flags_parser=parse_flags_with_usage, ): """Begins executing the program. Args: main: The main function to execute. It takes an single argument "argv", which is a list of command line arguments with parsed flags removed. If it returns an integer, it is used as the process's exit code. argv: A non-empty list of the command line arguments including program name, sys.argv is used if None. flags_parser: Callable[[List[Text]], Any], the function used to parse flags. The return value of this function is passed to `main` untouched. It must guarantee FLAGS is parsed after this function is called. - Parses command line flags with the flag module. - If there are any errors, prints usage(). - Calls main() with the remaining arguments. - If main() raises a UsageError, prints usage and the error message. """ try: args = _run_init( sys.argv if argv is None else argv, flags_parser, ) while _init_callbacks: callback = _init_callbacks.popleft() callback() try: _run_main(main, args) except UsageError as error: usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode) except: if FLAGS.pdb_post_mortem: traceback.print_exc() pdb.post_mortem() raise except Exception as e: _call_exception_handlers(e) raise
python
def run( main, argv=None, flags_parser=parse_flags_with_usage, ): try: args = _run_init( sys.argv if argv is None else argv, flags_parser, ) while _init_callbacks: callback = _init_callbacks.popleft() callback() try: _run_main(main, args) except UsageError as error: usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode) except: if FLAGS.pdb_post_mortem: traceback.print_exc() pdb.post_mortem() raise except Exception as e: _call_exception_handlers(e) raise
[ "def", "run", "(", "main", ",", "argv", "=", "None", ",", "flags_parser", "=", "parse_flags_with_usage", ",", ")", ":", "try", ":", "args", "=", "_run_init", "(", "sys", ".", "argv", "if", "argv", "is", "None", "else", "argv", ",", "flags_parser", ",",...
Begins executing the program. Args: main: The main function to execute. It takes an single argument "argv", which is a list of command line arguments with parsed flags removed. If it returns an integer, it is used as the process's exit code. argv: A non-empty list of the command line arguments including program name, sys.argv is used if None. flags_parser: Callable[[List[Text]], Any], the function used to parse flags. The return value of this function is passed to `main` untouched. It must guarantee FLAGS is parsed after this function is called. - Parses command line flags with the flag module. - If there are any errors, prints usage(). - Calls main() with the remaining arguments. - If main() raises a UsageError, prints usage and the error message.
[ "Begins", "executing", "the", "program", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L270-L310
234,257
abseil/abseil-py
absl/app.py
_run_init
def _run_init( argv, flags_parser, ): """Does one-time initialization and re-parses flags on rerun.""" if _run_init.done: return flags_parser(argv) command_name.make_process_name_useful() # Set up absl logging handler. logging.use_absl_handler() args = _register_and_parse_flags_with_usage( argv=argv, flags_parser=flags_parser, ) if faulthandler: try: faulthandler.enable() except Exception: # pylint: disable=broad-except # Some tests verify stderr output very closely, so don't print anything. # Disabled faulthandler is a low-impact error. pass _run_init.done = True return args
python
def _run_init( argv, flags_parser, ): if _run_init.done: return flags_parser(argv) command_name.make_process_name_useful() # Set up absl logging handler. logging.use_absl_handler() args = _register_and_parse_flags_with_usage( argv=argv, flags_parser=flags_parser, ) if faulthandler: try: faulthandler.enable() except Exception: # pylint: disable=broad-except # Some tests verify stderr output very closely, so don't print anything. # Disabled faulthandler is a low-impact error. pass _run_init.done = True return args
[ "def", "_run_init", "(", "argv", ",", "flags_parser", ",", ")", ":", "if", "_run_init", ".", "done", ":", "return", "flags_parser", "(", "argv", ")", "command_name", ".", "make_process_name_useful", "(", ")", "# Set up absl logging handler.", "logging", ".", "us...
Does one-time initialization and re-parses flags on rerun.
[ "Does", "one", "-", "time", "initialization", "and", "re", "-", "parses", "flags", "on", "rerun", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L339-L361
234,258
abseil/abseil-py
absl/app.py
install_exception_handler
def install_exception_handler(handler): """Installs an exception handler. Args: handler: ExceptionHandler, the exception handler to install. Raises: TypeError: Raised when the handler was not of the correct type. All installed exception handlers will be called if main() exits via an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt, FlagsError or UsageError. """ if not isinstance(handler, ExceptionHandler): raise TypeError('handler of type %s does not inherit from ExceptionHandler' % type(handler)) EXCEPTION_HANDLERS.append(handler)
python
def install_exception_handler(handler): if not isinstance(handler, ExceptionHandler): raise TypeError('handler of type %s does not inherit from ExceptionHandler' % type(handler)) EXCEPTION_HANDLERS.append(handler)
[ "def", "install_exception_handler", "(", "handler", ")", ":", "if", "not", "isinstance", "(", "handler", ",", "ExceptionHandler", ")", ":", "raise", "TypeError", "(", "'handler of type %s does not inherit from ExceptionHandler'", "%", "type", "(", "handler", ")", ")",...
Installs an exception handler. Args: handler: ExceptionHandler, the exception handler to install. Raises: TypeError: Raised when the handler was not of the correct type. All installed exception handlers will be called if main() exits via an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt, FlagsError or UsageError.
[ "Installs", "an", "exception", "handler", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L444-L460
234,259
abseil/abseil-py
absl/flags/_validators.py
register_validator
def register_validator(flag_name, checker, message='Flag validation failed', flag_values=_flagvalues.FLAGS): """Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: str, name of the flag to be checked. checker: callable, a function to validate the flag. input - A single positional argument: The value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). output - bool, True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise flags.ValidationError(desired_error_message). message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag_values: flags.FlagValues, optional FlagValues instance to validate against. Raises: AttributeError: Raised when flag_name is not registered as a valid flag name. """ v = SingleFlagValidator(flag_name, checker, message) _add_validator(flag_values, v)
python
def register_validator(flag_name, checker, message='Flag validation failed', flag_values=_flagvalues.FLAGS): v = SingleFlagValidator(flag_name, checker, message) _add_validator(flag_values, v)
[ "def", "register_validator", "(", "flag_name", ",", "checker", ",", "message", "=", "'Flag validation failed'", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ")", ":", "v", "=", "SingleFlagValidator", "(", "flag_name", ",", "checker", ",", "message", ")"...
Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: str, name of the flag to be checked. checker: callable, a function to validate the flag. input - A single positional argument: The value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). output - bool, True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise flags.ValidationError(desired_error_message). message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag_values: flags.FlagValues, optional FlagValues instance to validate against. Raises: AttributeError: Raised when flag_name is not registered as a valid flag name.
[ "Adds", "a", "constraint", "which", "will", "be", "enforced", "during", "program", "execution", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L196-L223
234,260
abseil/abseil-py
absl/flags/_validators.py
validator
def validator(flag_name, message='Flag validation failed', flag_values=_flagvalues.FLAGS): """A function decorator for defining a flag validator. Registers the decorated function as a validator for flag_name, e.g. @flags.validator('foo') def _CheckFoo(foo): ... See register_validator() for the specification of checker function. Args: flag_name: str, name of the flag to be checked. message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag_values: flags.FlagValues, optional FlagValues instance to validate against. Returns: A function decorator that registers its function argument as a validator. Raises: AttributeError: Raised when flag_name is not registered as a valid flag name. """ def decorate(function): register_validator(flag_name, function, message=message, flag_values=flag_values) return function return decorate
python
def validator(flag_name, message='Flag validation failed', flag_values=_flagvalues.FLAGS): def decorate(function): register_validator(flag_name, function, message=message, flag_values=flag_values) return function return decorate
[ "def", "validator", "(", "flag_name", ",", "message", "=", "'Flag validation failed'", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ")", ":", "def", "decorate", "(", "function", ")", ":", "register_validator", "(", "flag_name", ",", "function", ",", "...
A function decorator for defining a flag validator. Registers the decorated function as a validator for flag_name, e.g. @flags.validator('foo') def _CheckFoo(foo): ... See register_validator() for the specification of checker function. Args: flag_name: str, name of the flag to be checked. message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag_values: flags.FlagValues, optional FlagValues instance to validate against. Returns: A function decorator that registers its function argument as a validator. Raises: AttributeError: Raised when flag_name is not registered as a valid flag name.
[ "A", "function", "decorator", "for", "defining", "a", "flag", "validator", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L226-L257
234,261
abseil/abseil-py
absl/flags/_validators.py
mark_flags_as_required
def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS): """Ensures that flags are not None during program execution. Recommended usage: if __name__ == '__main__': flags.mark_flags_as_required(['flag1', 'flag2', 'flag3']) app.run() Args: flag_names: Sequence[str], names of the flags. flag_values: flags.FlagValues, optional FlagValues instance where the flags are defined. Raises: AttributeError: If any of flag name has not already been defined as a flag. """ for flag_name in flag_names: mark_flag_as_required(flag_name, flag_values)
python
def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS): for flag_name in flag_names: mark_flag_as_required(flag_name, flag_values)
[ "def", "mark_flags_as_required", "(", "flag_names", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ")", ":", "for", "flag_name", "in", "flag_names", ":", "mark_flag_as_required", "(", "flag_name", ",", "flag_values", ")" ]
Ensures that flags are not None during program execution. Recommended usage: if __name__ == '__main__': flags.mark_flags_as_required(['flag1', 'flag2', 'flag3']) app.run() Args: flag_names: Sequence[str], names of the flags. flag_values: flags.FlagValues, optional FlagValues instance where the flags are defined. Raises: AttributeError: If any of flag name has not already been defined as a flag.
[ "Ensures", "that", "flags", "are", "not", "None", "during", "program", "execution", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L367-L384
234,262
abseil/abseil-py
absl/flags/_validators.py
mark_flags_as_mutual_exclusive
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS): """Ensures that only one flag among flag_names is not None. Important note: This validator checks if flag values are None, and it does not distinguish between default and explicit values. Therefore, this validator does not make sense when applied to flags with default values other than None, including other false values (e.g. False, 0, '', []). That includes multi flags with a default value of [] instead of None. Args: flag_names: [str], names of the flags. required: bool. If true, exactly one of the flags must have a value other than None. Otherwise, at most one of the flags can have a value other than None, and it is valid for all of the flags to be None. flag_values: flags.FlagValues, optional FlagValues instance where the flags are defined. """ for flag_name in flag_names: if flag_values[flag_name].default is not None: warnings.warn( 'Flag --{} has a non-None default value. That does not make sense ' 'with mark_flags_as_mutual_exclusive, which checks whether the ' 'listed flags have a value other than None.'.format(flag_name)) def validate_mutual_exclusion(flags_dict): flag_count = sum(1 for val in flags_dict.values() if val is not None) if flag_count == 1 or (not required and flag_count == 0): return True raise _exceptions.ValidationError( '{} one of ({}) must have a value other than None.'.format( 'Exactly' if required else 'At most', ', '.join(flag_names))) register_multi_flags_validator( flag_names, validate_mutual_exclusion, flag_values=flag_values)
python
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS): for flag_name in flag_names: if flag_values[flag_name].default is not None: warnings.warn( 'Flag --{} has a non-None default value. That does not make sense ' 'with mark_flags_as_mutual_exclusive, which checks whether the ' 'listed flags have a value other than None.'.format(flag_name)) def validate_mutual_exclusion(flags_dict): flag_count = sum(1 for val in flags_dict.values() if val is not None) if flag_count == 1 or (not required and flag_count == 0): return True raise _exceptions.ValidationError( '{} one of ({}) must have a value other than None.'.format( 'Exactly' if required else 'At most', ', '.join(flag_names))) register_multi_flags_validator( flag_names, validate_mutual_exclusion, flag_values=flag_values)
[ "def", "mark_flags_as_mutual_exclusive", "(", "flag_names", ",", "required", "=", "False", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ")", ":", "for", "flag_name", "in", "flag_names", ":", "if", "flag_values", "[", "flag_name", "]", ".", "default", ...
Ensures that only one flag among flag_names is not None. Important note: This validator checks if flag values are None, and it does not distinguish between default and explicit values. Therefore, this validator does not make sense when applied to flags with default values other than None, including other false values (e.g. False, 0, '', []). That includes multi flags with a default value of [] instead of None. Args: flag_names: [str], names of the flags. required: bool. If true, exactly one of the flags must have a value other than None. Otherwise, at most one of the flags can have a value other than None, and it is valid for all of the flags to be None. flag_values: flags.FlagValues, optional FlagValues instance where the flags are defined.
[ "Ensures", "that", "only", "one", "flag", "among", "flag_names", "is", "not", "None", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L387-L421
234,263
abseil/abseil-py
absl/flags/_validators.py
mark_bool_flags_as_mutual_exclusive
def mark_bool_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS): """Ensures that only one flag among flag_names is True. Args: flag_names: [str], names of the flags. required: bool. If true, exactly one flag must be True. Otherwise, at most one flag can be True, and it is valid for all flags to be False. flag_values: flags.FlagValues, optional FlagValues instance where the flags are defined. """ for flag_name in flag_names: if not flag_values[flag_name].boolean: raise _exceptions.ValidationError( 'Flag --{} is not Boolean, which is required for flags used in ' 'mark_bool_flags_as_mutual_exclusive.'.format(flag_name)) def validate_boolean_mutual_exclusion(flags_dict): flag_count = sum(bool(val) for val in flags_dict.values()) if flag_count == 1 or (not required and flag_count == 0): return True raise _exceptions.ValidationError( '{} one of ({}) must be True.'.format( 'Exactly' if required else 'At most', ', '.join(flag_names))) register_multi_flags_validator( flag_names, validate_boolean_mutual_exclusion, flag_values=flag_values)
python
def mark_bool_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS): for flag_name in flag_names: if not flag_values[flag_name].boolean: raise _exceptions.ValidationError( 'Flag --{} is not Boolean, which is required for flags used in ' 'mark_bool_flags_as_mutual_exclusive.'.format(flag_name)) def validate_boolean_mutual_exclusion(flags_dict): flag_count = sum(bool(val) for val in flags_dict.values()) if flag_count == 1 or (not required and flag_count == 0): return True raise _exceptions.ValidationError( '{} one of ({}) must be True.'.format( 'Exactly' if required else 'At most', ', '.join(flag_names))) register_multi_flags_validator( flag_names, validate_boolean_mutual_exclusion, flag_values=flag_values)
[ "def", "mark_bool_flags_as_mutual_exclusive", "(", "flag_names", ",", "required", "=", "False", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ")", ":", "for", "flag_name", "in", "flag_names", ":", "if", "not", "flag_values", "[", "flag_name", "]", ".", ...
Ensures that only one flag among flag_names is True. Args: flag_names: [str], names of the flags. required: bool. If true, exactly one flag must be True. Otherwise, at most one flag can be True, and it is valid for all flags to be False. flag_values: flags.FlagValues, optional FlagValues instance where the flags are defined.
[ "Ensures", "that", "only", "one", "flag", "among", "flag_names", "is", "True", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L424-L450
234,264
abseil/abseil-py
absl/flags/_validators.py
_add_validator
def _add_validator(fv, validator_instance): """Register new flags validator to be checked. Args: fv: flags.FlagValues, the FlagValues instance to add the validator. validator_instance: validators.Validator, the validator to add. Raises: KeyError: Raised when validators work with a non-existing flag. """ for flag_name in validator_instance.get_flags_names(): fv[flag_name].validators.append(validator_instance)
python
def _add_validator(fv, validator_instance): for flag_name in validator_instance.get_flags_names(): fv[flag_name].validators.append(validator_instance)
[ "def", "_add_validator", "(", "fv", ",", "validator_instance", ")", ":", "for", "flag_name", "in", "validator_instance", ".", "get_flags_names", "(", ")", ":", "fv", "[", "flag_name", "]", ".", "validators", ".", "append", "(", "validator_instance", ")" ]
Register new flags validator to be checked. Args: fv: flags.FlagValues, the FlagValues instance to add the validator. validator_instance: validators.Validator, the validator to add. Raises: KeyError: Raised when validators work with a non-existing flag.
[ "Register", "new", "flags", "validator", "to", "be", "checked", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L453-L463
234,265
abseil/abseil-py
absl/flags/_validators.py
Validator.verify
def verify(self, flag_values): """Verifies that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: flags.FlagValues, the FlagValues instance to get flags from. Raises: Error: Raised if constraint is not satisfied. """ param = self._get_input_to_checker_function(flag_values) if not self.checker(param): raise _exceptions.ValidationError(self.message)
python
def verify(self, flag_values): param = self._get_input_to_checker_function(flag_values) if not self.checker(param): raise _exceptions.ValidationError(self.message)
[ "def", "verify", "(", "self", ",", "flag_values", ")", ":", "param", "=", "self", ".", "_get_input_to_checker_function", "(", "flag_values", ")", "if", "not", "self", ".", "checker", "(", "param", ")", ":", "raise", "_exceptions", ".", "ValidationError", "("...
Verifies that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: flags.FlagValues, the FlagValues instance to get flags from. Raises: Error: Raised if constraint is not satisfied.
[ "Verifies", "that", "constraint", "is", "satisfied", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L70-L82
234,266
abseil/abseil-py
absl/flags/_validators.py
MultiFlagsValidator._get_input_to_checker_function
def _get_input_to_checker_function(self, flag_values): """Given flag values, returns the input to be given to checker. Args: flag_values: flags.FlagValues, the FlagValues instance to get flags from. Returns: dict, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). """ return dict([key, flag_values[key].value] for key in self.flag_names)
python
def _get_input_to_checker_function(self, flag_values): return dict([key, flag_values[key].value] for key in self.flag_names)
[ "def", "_get_input_to_checker_function", "(", "self", ",", "flag_values", ")", ":", "return", "dict", "(", "[", "key", ",", "flag_values", "[", "key", "]", ".", "value", "]", "for", "key", "in", "self", ".", "flag_names", ")" ]
Given flag values, returns the input to be given to checker. Args: flag_values: flags.FlagValues, the FlagValues instance to get flags from. Returns: dict, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc).
[ "Given", "flag", "values", "returns", "the", "input", "to", "be", "given", "to", "checker", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L174-L183
234,267
abseil/abseil-py
absl/flags/_exceptions.py
DuplicateFlagError.from_flag
def from_flag(cls, flagname, flag_values, other_flag_values=None): """Creates a DuplicateFlagError by providing flag name and values. Args: flagname: str, the name of the flag being redefined. flag_values: FlagValues, the FlagValues instance containing the first definition of flagname. other_flag_values: FlagValues, if it is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. Returns: An instance of DuplicateFlagError. """ first_module = flag_values.find_module_defining_flag( flagname, default='<unknown>') if other_flag_values is None: second_module = _helpers.get_calling_module() else: second_module = other_flag_values.find_module_defining_flag( flagname, default='<unknown>') flag_summary = flag_values[flagname].help msg = ("The flag '%s' is defined twice. First from %s, Second from %s. " "Description from first occurrence: %s") % ( flagname, first_module, second_module, flag_summary) return cls(msg)
python
def from_flag(cls, flagname, flag_values, other_flag_values=None): first_module = flag_values.find_module_defining_flag( flagname, default='<unknown>') if other_flag_values is None: second_module = _helpers.get_calling_module() else: second_module = other_flag_values.find_module_defining_flag( flagname, default='<unknown>') flag_summary = flag_values[flagname].help msg = ("The flag '%s' is defined twice. First from %s, Second from %s. " "Description from first occurrence: %s") % ( flagname, first_module, second_module, flag_summary) return cls(msg)
[ "def", "from_flag", "(", "cls", ",", "flagname", ",", "flag_values", ",", "other_flag_values", "=", "None", ")", ":", "first_module", "=", "flag_values", ".", "find_module_defining_flag", "(", "flagname", ",", "default", "=", "'<unknown>'", ")", "if", "other_fla...
Creates a DuplicateFlagError by providing flag name and values. Args: flagname: str, the name of the flag being redefined. flag_values: FlagValues, the FlagValues instance containing the first definition of flagname. other_flag_values: FlagValues, if it is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. Returns: An instance of DuplicateFlagError.
[ "Creates", "a", "DuplicateFlagError", "by", "providing", "flag", "name", "and", "values", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_exceptions.py#L48-L75
234,268
abseil/abseil-py
absl/logging/__init__.py
set_verbosity
def set_verbosity(v): """Sets the logging verbosity. Causes all messages of level <= v to be logged, and all messages of level > v to be silently discarded. Args: v: int|str, the verbosity level as an integer or string. Legal string values are those that can be coerced to an integer as well as case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'. """ try: new_level = int(v) except ValueError: new_level = converter.ABSL_NAMES[v.upper()] FLAGS.verbosity = new_level
python
def set_verbosity(v): try: new_level = int(v) except ValueError: new_level = converter.ABSL_NAMES[v.upper()] FLAGS.verbosity = new_level
[ "def", "set_verbosity", "(", "v", ")", ":", "try", ":", "new_level", "=", "int", "(", "v", ")", "except", "ValueError", ":", "new_level", "=", "converter", ".", "ABSL_NAMES", "[", "v", ".", "upper", "(", ")", "]", "FLAGS", ".", "verbosity", "=", "new...
Sets the logging verbosity. Causes all messages of level <= v to be logged, and all messages of level > v to be silently discarded. Args: v: int|str, the verbosity level as an integer or string. Legal string values are those that can be coerced to an integer as well as case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'.
[ "Sets", "the", "logging", "verbosity", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L266-L281
234,269
abseil/abseil-py
absl/logging/__init__.py
set_stderrthreshold
def set_stderrthreshold(s): """Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. Raises: ValueError: Raised when s is an invalid value. """ if s in converter.ABSL_LEVELS: FLAGS.stderrthreshold = converter.ABSL_LEVELS[s] elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES: FLAGS.stderrthreshold = s else: raise ValueError( 'set_stderrthreshold only accepts integer absl logging level ' 'from -3 to 1, or case-insensitive string values ' "'debug', 'info', 'warning', 'error', and 'fatal'. " 'But found "{}" ({}).'.format(s, type(s)))
python
def set_stderrthreshold(s): if s in converter.ABSL_LEVELS: FLAGS.stderrthreshold = converter.ABSL_LEVELS[s] elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES: FLAGS.stderrthreshold = s else: raise ValueError( 'set_stderrthreshold only accepts integer absl logging level ' 'from -3 to 1, or case-insensitive string values ' "'debug', 'info', 'warning', 'error', and 'fatal'. " 'But found "{}" ({}).'.format(s, type(s)))
[ "def", "set_stderrthreshold", "(", "s", ")", ":", "if", "s", "in", "converter", ".", "ABSL_LEVELS", ":", "FLAGS", ".", "stderrthreshold", "=", "converter", ".", "ABSL_LEVELS", "[", "s", "]", "elif", "isinstance", "(", "s", ",", "str", ")", "and", "s", ...
Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. Raises: ValueError: Raised when s is an invalid value.
[ "Sets", "the", "stderr", "threshold", "to", "the", "value", "passed", "in", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L284-L304
234,270
abseil/abseil-py
absl/logging/__init__.py
log_every_n
def log_every_n(level, msg, n, *args): """Logs 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: int, the absl logging level at which to log. msg: str, the message to be logged. n: int, the number of times this should be called before it is logged. *args: The args to be substitued into the msg. """ count = _get_next_log_count_per_token(get_absl_logger().findCaller()) log_if(level, msg, not (count % n), *args)
python
def log_every_n(level, msg, n, *args): count = _get_next_log_count_per_token(get_absl_logger().findCaller()) log_if(level, msg, not (count % n), *args)
[ "def", "log_every_n", "(", "level", ",", "msg", ",", "n", ",", "*", "args", ")", ":", "count", "=", "_get_next_log_count_per_token", "(", "get_absl_logger", "(", ")", ".", "findCaller", "(", ")", ")", "log_if", "(", "level", ",", "msg", ",", "not", "("...
Logs 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: int, the absl logging level at which to log. msg: str, the message to be logged. n: int, the number of times this should be called before it is logged. *args: The args to be substitued into the msg.
[ "Logs", "msg", "%", "args", "at", "level", "level", "once", "per", "n", "times", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L367-L380
234,271
abseil/abseil-py
absl/logging/__init__.py
_seconds_have_elapsed
def _seconds_have_elapsed(token, num_seconds): """Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the first call for a given 'token'. Args: token: The token for which to look up the count. num_seconds: The number of seconds to test for. Returns: Whether it has been >= 'num_seconds' since 'token' was last requested. """ now = timeit.default_timer() then = _log_timer_per_token.get(token, None) if then is None or (now - then) >= num_seconds: _log_timer_per_token[token] = now return True else: return False
python
def _seconds_have_elapsed(token, num_seconds): now = timeit.default_timer() then = _log_timer_per_token.get(token, None) if then is None or (now - then) >= num_seconds: _log_timer_per_token[token] = now return True else: return False
[ "def", "_seconds_have_elapsed", "(", "token", ",", "num_seconds", ")", ":", "now", "=", "timeit", ".", "default_timer", "(", ")", "then", "=", "_log_timer_per_token", ".", "get", "(", "token", ",", "None", ")", "if", "then", "is", "None", "or", "(", "now...
Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the first call for a given 'token'. Args: token: The token for which to look up the count. num_seconds: The number of seconds to test for. Returns: Whether it has been >= 'num_seconds' since 'token' was last requested.
[ "Tests", "if", "num_seconds", "have", "passed", "since", "token", "was", "requested", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L389-L411
234,272
abseil/abseil-py
absl/logging/__init__.py
log_every_n_seconds
def log_every_n_seconds(level, msg, n_seconds, *args): """Logs 'msg % args' at level 'level' iff 'n_seconds' elapsed since last call. Logs the first call, logs subsequent calls if 'n' seconds have elapsed since the last logging call from the same call site (file + line). Not thread-safe. Args: level: int, the absl logging level at which to log. msg: str, the message to be logged. n_seconds: float or int, seconds which should elapse before logging again. *args: The args to be substitued into the msg. """ should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds) log_if(level, msg, should_log, *args)
python
def log_every_n_seconds(level, msg, n_seconds, *args): should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds) log_if(level, msg, should_log, *args)
[ "def", "log_every_n_seconds", "(", "level", ",", "msg", ",", "n_seconds", ",", "*", "args", ")", ":", "should_log", "=", "_seconds_have_elapsed", "(", "get_absl_logger", "(", ")", ".", "findCaller", "(", ")", ",", "n_seconds", ")", "log_if", "(", "level", ...
Logs 'msg % args' at level 'level' iff 'n_seconds' elapsed since last call. Logs the first call, logs subsequent calls if 'n' seconds have elapsed since the last logging call from the same call site (file + line). Not thread-safe. Args: level: int, the absl logging level at which to log. msg: str, the message to be logged. n_seconds: float or int, seconds which should elapse before logging again. *args: The args to be substitued into the msg.
[ "Logs", "msg", "%", "args", "at", "level", "level", "iff", "n_seconds", "elapsed", "since", "last", "call", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L414-L427
234,273
abseil/abseil-py
absl/logging/__init__.py
log_if
def log_if(level, msg, condition, *args): """Logs 'msg % args' at level 'level' only if condition is fulfilled.""" if condition: log(level, msg, *args)
python
def log_if(level, msg, condition, *args): if condition: log(level, msg, *args)
[ "def", "log_if", "(", "level", ",", "msg", ",", "condition", ",", "*", "args", ")", ":", "if", "condition", ":", "log", "(", "level", ",", "msg", ",", "*", "args", ")" ]
Logs 'msg % args' at level 'level' only if condition is fulfilled.
[ "Logs", "msg", "%", "args", "at", "level", "level", "only", "if", "condition", "is", "fulfilled", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L445-L448
234,274
abseil/abseil-py
absl/logging/__init__.py
log
def log(level, msg, *args, **kwargs): """Logs 'msg % args' at absl logging level 'level'. If no args are given just print msg, ignoring any interpolation specifiers. Args: level: int, the absl logging level at which to log the message (logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging level constants are also supported, callers should prefer explicit logging.vlog() calls for such purpose. msg: str, the message to be logged. *args: The args to be substitued into the msg. **kwargs: May contain exc_info to add exception traceback to message. """ if level > converter.ABSL_DEBUG: # Even though this function supports level that is greater than 1, users # should use logging.vlog instead for such cases. # Treat this as vlog, 1 is equivalent to DEBUG. standard_level = converter.STANDARD_DEBUG - (level - 1) else: if level < converter.ABSL_FATAL: level = converter.ABSL_FATAL standard_level = converter.absl_to_standard(level) _absl_logger.log(standard_level, msg, *args, **kwargs)
python
def log(level, msg, *args, **kwargs): if level > converter.ABSL_DEBUG: # Even though this function supports level that is greater than 1, users # should use logging.vlog instead for such cases. # Treat this as vlog, 1 is equivalent to DEBUG. standard_level = converter.STANDARD_DEBUG - (level - 1) else: if level < converter.ABSL_FATAL: level = converter.ABSL_FATAL standard_level = converter.absl_to_standard(level) _absl_logger.log(standard_level, msg, *args, **kwargs)
[ "def", "log", "(", "level", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "level", ">", "converter", ".", "ABSL_DEBUG", ":", "# Even though this function supports level that is greater than 1, users", "# should use logging.vlog instead for such ...
Logs 'msg % args' at absl logging level 'level'. If no args are given just print msg, ignoring any interpolation specifiers. Args: level: int, the absl logging level at which to log the message (logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging level constants are also supported, callers should prefer explicit logging.vlog() calls for such purpose. msg: str, the message to be logged. *args: The args to be substitued into the msg. **kwargs: May contain exc_info to add exception traceback to message.
[ "Logs", "msg", "%", "args", "at", "absl", "logging", "level", "level", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L451-L476
234,275
abseil/abseil-py
absl/logging/__init__.py
vlog_is_on
def vlog_is_on(level): """Checks if vlog is enabled for the given level in caller's source file. Args: level: int, the C++ verbose logging level at which to log the message, e.g. 1, 2, 3, 4... While absl level constants are also supported, callers should prefer level_debug|level_info|... calls for checking those. Returns: True if logging is turned on for that level. """ if level > converter.ABSL_DEBUG: # Even though this function supports level that is greater than 1, users # should use logging.vlog instead for such cases. # Treat this as vlog, 1 is equivalent to DEBUG. standard_level = converter.STANDARD_DEBUG - (level - 1) else: if level < converter.ABSL_FATAL: level = converter.ABSL_FATAL standard_level = converter.absl_to_standard(level) return _absl_logger.isEnabledFor(standard_level)
python
def vlog_is_on(level): if level > converter.ABSL_DEBUG: # Even though this function supports level that is greater than 1, users # should use logging.vlog instead for such cases. # Treat this as vlog, 1 is equivalent to DEBUG. standard_level = converter.STANDARD_DEBUG - (level - 1) else: if level < converter.ABSL_FATAL: level = converter.ABSL_FATAL standard_level = converter.absl_to_standard(level) return _absl_logger.isEnabledFor(standard_level)
[ "def", "vlog_is_on", "(", "level", ")", ":", "if", "level", ">", "converter", ".", "ABSL_DEBUG", ":", "# Even though this function supports level that is greater than 1, users", "# should use logging.vlog instead for such cases.", "# Treat this as vlog, 1 is equivalent to DEBUG.", "s...
Checks if vlog is enabled for the given level in caller's source file. Args: level: int, the C++ verbose logging level at which to log the message, e.g. 1, 2, 3, 4... While absl level constants are also supported, callers should prefer level_debug|level_info|... calls for checking those. Returns: True if logging is turned on for that level.
[ "Checks", "if", "vlog", "is", "enabled", "for", "the", "given", "level", "in", "caller", "s", "source", "file", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L493-L515
234,276
abseil/abseil-py
absl/logging/__init__.py
get_log_file_name
def get_log_file_name(level=INFO): """Returns the name of the log file. For Python logging, only one file is used and level is ignored. And it returns empty string if it logs to stderr/stdout or the log stream has no `name` attribute. Args: level: int, the absl.logging level. Raises: ValueError: Raised when `level` has an invalid value. """ if level not in converter.ABSL_LEVELS: raise ValueError('Invalid absl.logging level {}'.format(level)) stream = get_absl_handler().python_handler.stream if (stream == sys.stderr or stream == sys.stdout or not hasattr(stream, 'name')): return '' else: return stream.name
python
def get_log_file_name(level=INFO): if level not in converter.ABSL_LEVELS: raise ValueError('Invalid absl.logging level {}'.format(level)) stream = get_absl_handler().python_handler.stream if (stream == sys.stderr or stream == sys.stdout or not hasattr(stream, 'name')): return '' else: return stream.name
[ "def", "get_log_file_name", "(", "level", "=", "INFO", ")", ":", "if", "level", "not", "in", "converter", ".", "ABSL_LEVELS", ":", "raise", "ValueError", "(", "'Invalid absl.logging level {}'", ".", "format", "(", "level", ")", ")", "stream", "=", "get_absl_ha...
Returns the name of the log file. For Python logging, only one file is used and level is ignored. And it returns empty string if it logs to stderr/stdout or the log stream has no `name` attribute. Args: level: int, the absl.logging level. Raises: ValueError: Raised when `level` has an invalid value.
[ "Returns", "the", "name", "of", "the", "log", "file", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L546-L566
234,277
abseil/abseil-py
absl/logging/__init__.py
find_log_dir_and_names
def find_log_dir_and_names(program_name=None, log_dir=None): """Computes the directory and filename prefix for log file. Args: program_name: str|None, the filename part of the path to the program that is running without its extension. e.g: if your program is called 'usr/bin/foobar.py' this method should probably be called with program_name='foobar' However, this is just a convention, you can pass in any string you want, and it will be used as part of the log filename. If you don't pass in anything, the default behavior is as described in the example. In python standard logging mode, the program_name will be prepended with py_ if it is the program_name argument is omitted. log_dir: str|None, the desired log directory. Returns: (log_dir, file_prefix, symlink_prefix) """ if not program_name: # Strip the extension (foobar.par becomes foobar, and # fubar.py becomes fubar). We do this so that the log # file names are similar to C++ log file names. program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] # Prepend py_ to files so that python code gets a unique file, and # so that C++ libraries do not try to write to the same log files as us. program_name = 'py_%s' % program_name actual_log_dir = find_log_dir(log_dir=log_dir) try: username = getpass.getuser() except KeyError: # This can happen, e.g. when running under docker w/o passwd file. if hasattr(os, 'getuid'): # Windows doesn't have os.getuid username = str(os.getuid()) else: username = 'unknown' hostname = socket.gethostname() file_prefix = '%s.%s.%s.log' % (program_name, hostname, username) return actual_log_dir, file_prefix, program_name
python
def find_log_dir_and_names(program_name=None, log_dir=None): if not program_name: # Strip the extension (foobar.par becomes foobar, and # fubar.py becomes fubar). We do this so that the log # file names are similar to C++ log file names. program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] # Prepend py_ to files so that python code gets a unique file, and # so that C++ libraries do not try to write to the same log files as us. program_name = 'py_%s' % program_name actual_log_dir = find_log_dir(log_dir=log_dir) try: username = getpass.getuser() except KeyError: # This can happen, e.g. when running under docker w/o passwd file. if hasattr(os, 'getuid'): # Windows doesn't have os.getuid username = str(os.getuid()) else: username = 'unknown' hostname = socket.gethostname() file_prefix = '%s.%s.%s.log' % (program_name, hostname, username) return actual_log_dir, file_prefix, program_name
[ "def", "find_log_dir_and_names", "(", "program_name", "=", "None", ",", "log_dir", "=", "None", ")", ":", "if", "not", "program_name", ":", "# Strip the extension (foobar.par becomes foobar, and", "# fubar.py becomes fubar). We do this so that the log", "# file names are similar ...
Computes the directory and filename prefix for log file. Args: program_name: str|None, the filename part of the path to the program that is running without its extension. e.g: if your program is called 'usr/bin/foobar.py' this method should probably be called with program_name='foobar' However, this is just a convention, you can pass in any string you want, and it will be used as part of the log filename. If you don't pass in anything, the default behavior is as described in the example. In python standard logging mode, the program_name will be prepended with py_ if it is the program_name argument is omitted. log_dir: str|None, the desired log directory. Returns: (log_dir, file_prefix, symlink_prefix)
[ "Computes", "the", "directory", "and", "filename", "prefix", "for", "log", "file", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L569-L611
234,278
abseil/abseil-py
absl/logging/__init__.py
find_log_dir
def find_log_dir(log_dir=None): """Returns the most suitable directory to put log files into. Args: log_dir: str|None, if specified, the logfile(s) will be created in that directory. Otherwise if the --log_dir command-line flag is provided, the logfile will be created in that directory. Otherwise the logfile will be created in a standard location. """ # Get a list of possible log dirs (will try to use them in order). if log_dir: # log_dir was explicitly specified as an arg, so use it and it alone. dirs = [log_dir] elif FLAGS['log_dir'].value: # log_dir flag was provided, so use it and it alone (this mimics the # behavior of the same flag in logging.cc). dirs = [FLAGS['log_dir'].value] else: dirs = ['/tmp/', './'] # Find the first usable log dir. for d in dirs: if os.path.isdir(d) and os.access(d, os.W_OK): return d _absl_logger.fatal("Can't find a writable directory for logs, tried %s", dirs)
python
def find_log_dir(log_dir=None): # Get a list of possible log dirs (will try to use them in order). if log_dir: # log_dir was explicitly specified as an arg, so use it and it alone. dirs = [log_dir] elif FLAGS['log_dir'].value: # log_dir flag was provided, so use it and it alone (this mimics the # behavior of the same flag in logging.cc). dirs = [FLAGS['log_dir'].value] else: dirs = ['/tmp/', './'] # Find the first usable log dir. for d in dirs: if os.path.isdir(d) and os.access(d, os.W_OK): return d _absl_logger.fatal("Can't find a writable directory for logs, tried %s", dirs)
[ "def", "find_log_dir", "(", "log_dir", "=", "None", ")", ":", "# Get a list of possible log dirs (will try to use them in order).", "if", "log_dir", ":", "# log_dir was explicitly specified as an arg, so use it and it alone.", "dirs", "=", "[", "log_dir", "]", "elif", "FLAGS", ...
Returns the most suitable directory to put log files into. Args: log_dir: str|None, if specified, the logfile(s) will be created in that directory. Otherwise if the --log_dir command-line flag is provided, the logfile will be created in that directory. Otherwise the logfile will be created in a standard location.
[ "Returns", "the", "most", "suitable", "directory", "to", "put", "log", "files", "into", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L614-L638
234,279
abseil/abseil-py
absl/logging/__init__.py
get_absl_log_prefix
def get_absl_log_prefix(record): """Returns the absl log prefix for the log record. Args: record: logging.LogRecord, the record to get prefix for. """ created_tuple = time.localtime(record.created) created_microsecond = int(record.created % 1.0 * 1e6) critical_prefix = '' level = record.levelno if _is_non_absl_fatal_record(record): # When the level is FATAL, but not logged from absl, lower the level so # it's treated as ERROR. level = logging.ERROR critical_prefix = _CRITICAL_PREFIX severity = converter.get_initial_for_level(level) return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % ( severity, created_tuple.tm_mon, created_tuple.tm_mday, created_tuple.tm_hour, created_tuple.tm_min, created_tuple.tm_sec, created_microsecond, _get_thread_id(), record.filename, record.lineno, critical_prefix)
python
def get_absl_log_prefix(record): created_tuple = time.localtime(record.created) created_microsecond = int(record.created % 1.0 * 1e6) critical_prefix = '' level = record.levelno if _is_non_absl_fatal_record(record): # When the level is FATAL, but not logged from absl, lower the level so # it's treated as ERROR. level = logging.ERROR critical_prefix = _CRITICAL_PREFIX severity = converter.get_initial_for_level(level) return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % ( severity, created_tuple.tm_mon, created_tuple.tm_mday, created_tuple.tm_hour, created_tuple.tm_min, created_tuple.tm_sec, created_microsecond, _get_thread_id(), record.filename, record.lineno, critical_prefix)
[ "def", "get_absl_log_prefix", "(", "record", ")", ":", "created_tuple", "=", "time", ".", "localtime", "(", "record", ".", "created", ")", "created_microsecond", "=", "int", "(", "record", ".", "created", "%", "1.0", "*", "1e6", ")", "critical_prefix", "=", ...
Returns the absl log prefix for the log record. Args: record: logging.LogRecord, the record to get prefix for.
[ "Returns", "the", "absl", "log", "prefix", "for", "the", "log", "record", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L641-L670
234,280
abseil/abseil-py
absl/logging/__init__.py
skip_log_prefix
def skip_log_prefix(func): """Skips reporting the prefix of a given function or name by ABSLLogger. This is a convenience wrapper function / decorator for `ABSLLogger.register_frame_to_skip`. If a callable function is provided, only that function will be skipped. If a function name is provided, all functions with the same name in the file that this is called in will be skipped. This can be used as a decorator of the intended function to be skipped. Args: func: Callable function or its name as a string. Returns: func (the input, unchanged). Raises: ValueError: The input is callable but does not have a function code object. TypeError: The input is neither callable nor a string. """ if callable(func): func_code = getattr(func, '__code__', None) if func_code is None: raise ValueError('Input callable does not have a function code object.') file_name = func_code.co_filename func_name = func_code.co_name func_lineno = func_code.co_firstlineno elif isinstance(func, six.string_types): file_name = get_absl_logger().findCaller()[0] func_name = func func_lineno = None else: raise TypeError('Input is neither callable nor a string.') ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno) return func
python
def skip_log_prefix(func): if callable(func): func_code = getattr(func, '__code__', None) if func_code is None: raise ValueError('Input callable does not have a function code object.') file_name = func_code.co_filename func_name = func_code.co_name func_lineno = func_code.co_firstlineno elif isinstance(func, six.string_types): file_name = get_absl_logger().findCaller()[0] func_name = func func_lineno = None else: raise TypeError('Input is neither callable nor a string.') ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno) return func
[ "def", "skip_log_prefix", "(", "func", ")", ":", "if", "callable", "(", "func", ")", ":", "func_code", "=", "getattr", "(", "func", ",", "'__code__'", ",", "None", ")", "if", "func_code", "is", "None", ":", "raise", "ValueError", "(", "'Input callable does...
Skips reporting the prefix of a given function or name by ABSLLogger. This is a convenience wrapper function / decorator for `ABSLLogger.register_frame_to_skip`. If a callable function is provided, only that function will be skipped. If a function name is provided, all functions with the same name in the file that this is called in will be skipped. This can be used as a decorator of the intended function to be skipped. Args: func: Callable function or its name as a string. Returns: func (the input, unchanged). Raises: ValueError: The input is callable but does not have a function code object. TypeError: The input is neither callable nor a string.
[ "Skips", "reporting", "the", "prefix", "of", "a", "given", "function", "or", "name", "by", "ABSLLogger", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L673-L709
234,281
abseil/abseil-py
absl/logging/__init__.py
use_absl_handler
def use_absl_handler(): """Uses the ABSL logging handler for logging if not yet configured. The absl handler is already attached to root if there are no other handlers attached when importing this module. Otherwise, this method is called in app.run() so absl handler is used. """ absl_handler = get_absl_handler() if absl_handler not in logging.root.handlers: logging.root.addHandler(absl_handler) FLAGS['verbosity']._update_logging_levels()
python
def use_absl_handler(): absl_handler = get_absl_handler() if absl_handler not in logging.root.handlers: logging.root.addHandler(absl_handler) FLAGS['verbosity']._update_logging_levels()
[ "def", "use_absl_handler", "(", ")", ":", "absl_handler", "=", "get_absl_handler", "(", ")", "if", "absl_handler", "not", "in", "logging", ".", "root", ".", "handlers", ":", "logging", ".", "root", ".", "addHandler", "(", "absl_handler", ")", "FLAGS", "[", ...
Uses the ABSL logging handler for logging if not yet configured. The absl handler is already attached to root if there are no other handlers attached when importing this module. Otherwise, this method is called in app.run() so absl handler is used.
[ "Uses", "the", "ABSL", "logging", "handler", "for", "logging", "if", "not", "yet", "configured", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1114-L1125
234,282
abseil/abseil-py
absl/logging/__init__.py
_initialize
def _initialize(): """Initializes loggers and handlers.""" global _absl_logger, _absl_handler if _absl_logger: return original_logger_class = logging.getLoggerClass() logging.setLoggerClass(ABSLLogger) _absl_logger = logging.getLogger('absl') logging.setLoggerClass(original_logger_class) python_logging_formatter = PythonFormatter() _absl_handler = ABSLHandler(python_logging_formatter) # The absl handler logs to stderr by default. To prevent double logging to # stderr, the following code tries its best to remove other handlers that emit # to stderr. Those handlers are most commonly added when logging.info/debug is # called before importing this module. handlers = [ h for h in logging.root.handlers if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr] for h in handlers: logging.root.removeHandler(h) # The absl handler will always be attached to root, not the absl logger. if not logging.root.handlers: # Attach the absl handler at import time when there are no other handlers. # Otherwise it means users have explicitly configured logging, and the absl # handler will only be attached later in app.run(). For App Engine apps, # the absl handler is not used. logging.root.addHandler(_absl_handler)
python
def _initialize(): global _absl_logger, _absl_handler if _absl_logger: return original_logger_class = logging.getLoggerClass() logging.setLoggerClass(ABSLLogger) _absl_logger = logging.getLogger('absl') logging.setLoggerClass(original_logger_class) python_logging_formatter = PythonFormatter() _absl_handler = ABSLHandler(python_logging_formatter) # The absl handler logs to stderr by default. To prevent double logging to # stderr, the following code tries its best to remove other handlers that emit # to stderr. Those handlers are most commonly added when logging.info/debug is # called before importing this module. handlers = [ h for h in logging.root.handlers if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr] for h in handlers: logging.root.removeHandler(h) # The absl handler will always be attached to root, not the absl logger. if not logging.root.handlers: # Attach the absl handler at import time when there are no other handlers. # Otherwise it means users have explicitly configured logging, and the absl # handler will only be attached later in app.run(). For App Engine apps, # the absl handler is not used. logging.root.addHandler(_absl_handler)
[ "def", "_initialize", "(", ")", ":", "global", "_absl_logger", ",", "_absl_handler", "if", "_absl_logger", ":", "return", "original_logger_class", "=", "logging", ".", "getLoggerClass", "(", ")", "logging", ".", "setLoggerClass", "(", "ABSLLogger", ")", "_absl_log...
Initializes loggers and handlers.
[ "Initializes", "loggers", "and", "handlers", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1128-L1159
234,283
abseil/abseil-py
absl/logging/__init__.py
_VerbosityFlag._update_logging_levels
def _update_logging_levels(self): """Updates absl logging levels to the current verbosity.""" if not _absl_logger: return if self._value <= converter.ABSL_DEBUG: standard_verbosity = converter.absl_to_standard(self._value) else: # --verbosity is set to higher than 1 for vlog. standard_verbosity = logging.DEBUG - (self._value - 1) # Also update root level when absl_handler is used. if _absl_handler in logging.root.handlers: logging.root.setLevel(standard_verbosity)
python
def _update_logging_levels(self): if not _absl_logger: return if self._value <= converter.ABSL_DEBUG: standard_verbosity = converter.absl_to_standard(self._value) else: # --verbosity is set to higher than 1 for vlog. standard_verbosity = logging.DEBUG - (self._value - 1) # Also update root level when absl_handler is used. if _absl_handler in logging.root.handlers: logging.root.setLevel(standard_verbosity)
[ "def", "_update_logging_levels", "(", "self", ")", ":", "if", "not", "_absl_logger", ":", "return", "if", "self", ".", "_value", "<=", "converter", ".", "ABSL_DEBUG", ":", "standard_verbosity", "=", "converter", ".", "absl_to_standard", "(", "self", ".", "_val...
Updates absl logging levels to the current verbosity.
[ "Updates", "absl", "logging", "levels", "to", "the", "current", "verbosity", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L176-L189
234,284
abseil/abseil-py
absl/logging/__init__.py
PythonHandler.start_logging_to_file
def start_logging_to_file(self, program_name=None, log_dir=None): """Starts logging messages to files instead of standard error.""" FLAGS.logtostderr = False actual_log_dir, file_prefix, symlink_prefix = find_log_dir_and_names( program_name=program_name, log_dir=log_dir) basename = '%s.INFO.%s.%d' % ( file_prefix, time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time())), os.getpid()) filename = os.path.join(actual_log_dir, basename) if six.PY2: self.stream = open(filename, 'a') else: self.stream = open(filename, 'a', encoding='utf-8') # os.symlink is not available on Windows Python 2. if getattr(os, 'symlink', None): # Create a symlink to the log file with a canonical name. symlink = os.path.join(actual_log_dir, symlink_prefix + '.INFO') try: if os.path.islink(symlink): os.unlink(symlink) os.symlink(os.path.basename(filename), symlink) except EnvironmentError: # If it fails, we're sad but it's no error. Commonly, this # fails because the symlink was created by another user and so # we can't modify it pass
python
def start_logging_to_file(self, program_name=None, log_dir=None): FLAGS.logtostderr = False actual_log_dir, file_prefix, symlink_prefix = find_log_dir_and_names( program_name=program_name, log_dir=log_dir) basename = '%s.INFO.%s.%d' % ( file_prefix, time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time())), os.getpid()) filename = os.path.join(actual_log_dir, basename) if six.PY2: self.stream = open(filename, 'a') else: self.stream = open(filename, 'a', encoding='utf-8') # os.symlink is not available on Windows Python 2. if getattr(os, 'symlink', None): # Create a symlink to the log file with a canonical name. symlink = os.path.join(actual_log_dir, symlink_prefix + '.INFO') try: if os.path.islink(symlink): os.unlink(symlink) os.symlink(os.path.basename(filename), symlink) except EnvironmentError: # If it fails, we're sad but it's no error. Commonly, this # fails because the symlink was created by another user and so # we can't modify it pass
[ "def", "start_logging_to_file", "(", "self", ",", "program_name", "=", "None", ",", "log_dir", "=", "None", ")", ":", "FLAGS", ".", "logtostderr", "=", "False", "actual_log_dir", ",", "file_prefix", ",", "symlink_prefix", "=", "find_log_dir_and_names", "(", "pro...
Starts logging messages to files instead of standard error.
[ "Starts", "logging", "messages", "to", "files", "instead", "of", "standard", "error", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L733-L763
234,285
abseil/abseil-py
absl/logging/__init__.py
PythonHandler.flush
def flush(self): """Flushes all log files.""" self.acquire() try: self.stream.flush() except (EnvironmentError, ValueError): # A ValueError is thrown if we try to flush a closed file. pass finally: self.release()
python
def flush(self): self.acquire() try: self.stream.flush() except (EnvironmentError, ValueError): # A ValueError is thrown if we try to flush a closed file. pass finally: self.release()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "self", ".", "stream", ".", "flush", "(", ")", "except", "(", "EnvironmentError", ",", "ValueError", ")", ":", "# A ValueError is thrown if we try to flush a closed file.", "p...
Flushes all log files.
[ "Flushes", "all", "log", "files", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L772-L781
234,286
abseil/abseil-py
absl/logging/__init__.py
PythonHandler._log_to_stderr
def _log_to_stderr(self, record): """Emits the record to stderr. This temporarily sets the handler stream to stderr, calls StreamHandler.emit, then reverts the stream back. Args: record: logging.LogRecord, the record to log. """ # emit() is protected by a lock in logging.Handler, so we don't need to # protect here again. old_stream = self.stream self.stream = sys.stderr try: super(PythonHandler, self).emit(record) finally: self.stream = old_stream
python
def _log_to_stderr(self, record): # emit() is protected by a lock in logging.Handler, so we don't need to # protect here again. old_stream = self.stream self.stream = sys.stderr try: super(PythonHandler, self).emit(record) finally: self.stream = old_stream
[ "def", "_log_to_stderr", "(", "self", ",", "record", ")", ":", "# emit() is protected by a lock in logging.Handler, so we don't need to", "# protect here again.", "old_stream", "=", "self", ".", "stream", "self", ".", "stream", "=", "sys", ".", "stderr", "try", ":", "...
Emits the record to stderr. This temporarily sets the handler stream to stderr, calls StreamHandler.emit, then reverts the stream back. Args: record: logging.LogRecord, the record to log.
[ "Emits", "the", "record", "to", "stderr", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L783-L799
234,287
abseil/abseil-py
absl/logging/__init__.py
PythonHandler.emit
def emit(self, record): """Prints a record out to some streams. If FLAGS.logtostderr is set, it will print to sys.stderr ONLY. If FLAGS.alsologtostderr is set, it will print to sys.stderr. If FLAGS.logtostderr is not set, it will log to the stream associated with the current thread. Args: record: logging.LogRecord, the record to emit. """ # People occasionally call logging functions at import time before # our flags may have even been defined yet, let alone even parsed, as we # rely on the C++ side to define some flags for us and app init to # deal with parsing. Match the C++ library behavior of notify and emit # such messages to stderr. It encourages people to clean-up and does # not hide the message. level = record.levelno if not FLAGS.is_parsed(): # Also implies "before flag has been defined". global _warn_preinit_stderr if _warn_preinit_stderr: sys.stderr.write( 'WARNING: Logging before flag parsing goes to stderr.\n') _warn_preinit_stderr = False self._log_to_stderr(record) elif FLAGS['logtostderr'].value: self._log_to_stderr(record) else: super(PythonHandler, self).emit(record) stderr_threshold = converter.string_to_standard( FLAGS['stderrthreshold'].value) if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and self.stream != sys.stderr): self._log_to_stderr(record) # Die when the record is created from ABSLLogger and level is FATAL. if _is_absl_fatal_record(record): self.flush() # Flush the log before dying. # In threaded python, sys.exit() from a non-main thread only # exits the thread in question. os.abort()
python
def emit(self, record): # People occasionally call logging functions at import time before # our flags may have even been defined yet, let alone even parsed, as we # rely on the C++ side to define some flags for us and app init to # deal with parsing. Match the C++ library behavior of notify and emit # such messages to stderr. It encourages people to clean-up and does # not hide the message. level = record.levelno if not FLAGS.is_parsed(): # Also implies "before flag has been defined". global _warn_preinit_stderr if _warn_preinit_stderr: sys.stderr.write( 'WARNING: Logging before flag parsing goes to stderr.\n') _warn_preinit_stderr = False self._log_to_stderr(record) elif FLAGS['logtostderr'].value: self._log_to_stderr(record) else: super(PythonHandler, self).emit(record) stderr_threshold = converter.string_to_standard( FLAGS['stderrthreshold'].value) if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and self.stream != sys.stderr): self._log_to_stderr(record) # Die when the record is created from ABSLLogger and level is FATAL. if _is_absl_fatal_record(record): self.flush() # Flush the log before dying. # In threaded python, sys.exit() from a non-main thread only # exits the thread in question. os.abort()
[ "def", "emit", "(", "self", ",", "record", ")", ":", "# People occasionally call logging functions at import time before", "# our flags may have even been defined yet, let alone even parsed, as we", "# rely on the C++ side to define some flags for us and app init to", "# deal with parsing. Ma...
Prints a record out to some streams. If FLAGS.logtostderr is set, it will print to sys.stderr ONLY. If FLAGS.alsologtostderr is set, it will print to sys.stderr. If FLAGS.logtostderr is not set, it will log to the stream associated with the current thread. Args: record: logging.LogRecord, the record to emit.
[ "Prints", "a", "record", "out", "to", "some", "streams", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L801-L841
234,288
abseil/abseil-py
absl/logging/__init__.py
PythonHandler.close
def close(self): """Closes the stream to which we are writing.""" self.acquire() try: self.flush() try: # Do not close the stream if it's sys.stderr|stdout. They may be # redirected or overridden to files, which should be managed by users # explicitly. if self.stream not in (sys.stderr, sys.stdout) and ( not hasattr(self.stream, 'isatty') or not self.stream.isatty()): self.stream.close() except ValueError: # A ValueError is thrown if we try to run isatty() on a closed file. pass super(PythonHandler, self).close() finally: self.release()
python
def close(self): self.acquire() try: self.flush() try: # Do not close the stream if it's sys.stderr|stdout. They may be # redirected or overridden to files, which should be managed by users # explicitly. if self.stream not in (sys.stderr, sys.stdout) and ( not hasattr(self.stream, 'isatty') or not self.stream.isatty()): self.stream.close() except ValueError: # A ValueError is thrown if we try to run isatty() on a closed file. pass super(PythonHandler, self).close() finally: self.release()
[ "def", "close", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "self", ".", "flush", "(", ")", "try", ":", "# Do not close the stream if it's sys.stderr|stdout. They may be", "# redirected or overridden to files, which should be managed by users", "#...
Closes the stream to which we are writing.
[ "Closes", "the", "stream", "to", "which", "we", "are", "writing", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L843-L860
234,289
abseil/abseil-py
absl/logging/__init__.py
PythonFormatter.format
def format(self, record): """Appends the message from the record to the results of the prefix. Args: record: logging.LogRecord, the record to be formatted. Returns: The formatted string representing the record. """ if (not FLAGS['showprefixforinfo'].value and FLAGS['verbosity'].value == converter.ABSL_INFO and record.levelno == logging.INFO and _absl_handler.python_handler.stream == sys.stderr): prefix = '' else: prefix = get_absl_log_prefix(record) return prefix + super(PythonFormatter, self).format(record)
python
def format(self, record): if (not FLAGS['showprefixforinfo'].value and FLAGS['verbosity'].value == converter.ABSL_INFO and record.levelno == logging.INFO and _absl_handler.python_handler.stream == sys.stderr): prefix = '' else: prefix = get_absl_log_prefix(record) return prefix + super(PythonFormatter, self).format(record)
[ "def", "format", "(", "self", ",", "record", ")", ":", "if", "(", "not", "FLAGS", "[", "'showprefixforinfo'", "]", ".", "value", "and", "FLAGS", "[", "'verbosity'", "]", ".", "value", "==", "converter", ".", "ABSL_INFO", "and", "record", ".", "levelno", ...
Appends the message from the record to the results of the prefix. Args: record: logging.LogRecord, the record to be formatted. Returns: The formatted string representing the record.
[ "Appends", "the", "message", "from", "the", "record", "to", "the", "results", "of", "the", "prefix", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L912-L928
234,290
abseil/abseil-py
absl/logging/__init__.py
ABSLLogger.findCaller
def findCaller(self, stack_info=False): """Finds the frame of the calling method on the stack. This method skips any frames registered with the ABSLLogger and any methods from this file, and whatever method is currently being used to generate the prefix for the log line. Then it returns the file name, line number, and method name of the calling method. An optional fourth item may be returned, callers who only need things from the first three are advised to always slice or index the result rather than using direct unpacking assignment. Args: stack_info: bool, when True, include the stack trace as a fourth item returned. On Python 3 there are always four items returned - the fourth will be None when this is False. On Python 2 the stdlib base class API only returns three items. We do the same when this new parameter is unspecified or False for compatibility. Returns: (filename, lineno, methodname[, sinfo]) of the calling method. """ f_to_skip = ABSLLogger._frames_to_skip # Use sys._getframe(2) instead of logging.currentframe(), it's slightly # faster because there is one less frame to traverse. frame = sys._getframe(2) # pylint: disable=protected-access while frame: code = frame.f_code if (_LOGGING_FILE_PREFIX not in code.co_filename and (code.co_filename, code.co_name, code.co_firstlineno) not in f_to_skip and (code.co_filename, code.co_name) not in f_to_skip): if six.PY2 and not stack_info: return (code.co_filename, frame.f_lineno, code.co_name) else: sinfo = None if stack_info: out = io.StringIO() out.write(u'Stack (most recent call last):\n') traceback.print_stack(frame, file=out) sinfo = out.getvalue().rstrip(u'\n') return (code.co_filename, frame.f_lineno, code.co_name, sinfo) frame = frame.f_back
python
def findCaller(self, stack_info=False): f_to_skip = ABSLLogger._frames_to_skip # Use sys._getframe(2) instead of logging.currentframe(), it's slightly # faster because there is one less frame to traverse. frame = sys._getframe(2) # pylint: disable=protected-access while frame: code = frame.f_code if (_LOGGING_FILE_PREFIX not in code.co_filename and (code.co_filename, code.co_name, code.co_firstlineno) not in f_to_skip and (code.co_filename, code.co_name) not in f_to_skip): if six.PY2 and not stack_info: return (code.co_filename, frame.f_lineno, code.co_name) else: sinfo = None if stack_info: out = io.StringIO() out.write(u'Stack (most recent call last):\n') traceback.print_stack(frame, file=out) sinfo = out.getvalue().rstrip(u'\n') return (code.co_filename, frame.f_lineno, code.co_name, sinfo) frame = frame.f_back
[ "def", "findCaller", "(", "self", ",", "stack_info", "=", "False", ")", ":", "f_to_skip", "=", "ABSLLogger", ".", "_frames_to_skip", "# Use sys._getframe(2) instead of logging.currentframe(), it's slightly", "# faster because there is one less frame to traverse.", "frame", "=", ...
Finds the frame of the calling method on the stack. This method skips any frames registered with the ABSLLogger and any methods from this file, and whatever method is currently being used to generate the prefix for the log line. Then it returns the file name, line number, and method name of the calling method. An optional fourth item may be returned, callers who only need things from the first three are advised to always slice or index the result rather than using direct unpacking assignment. Args: stack_info: bool, when True, include the stack trace as a fourth item returned. On Python 3 there are always four items returned - the fourth will be None when this is False. On Python 2 the stdlib base class API only returns three items. We do the same when this new parameter is unspecified or False for compatibility. Returns: (filename, lineno, methodname[, sinfo]) of the calling method.
[ "Finds", "the", "frame", "of", "the", "calling", "method", "on", "the", "stack", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L945-L988
234,291
abseil/abseil-py
absl/logging/__init__.py
ABSLLogger.fatal
def fatal(self, msg, *args, **kwargs): """Logs 'msg % args' with severity 'FATAL'.""" self.log(logging.FATAL, msg, *args, **kwargs)
python
def fatal(self, msg, *args, **kwargs): self.log(logging.FATAL, msg, *args, **kwargs)
[ "def", "fatal", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", "(", "logging", ".", "FATAL", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Logs 'msg % args' with severity 'FATAL'.
[ "Logs", "msg", "%", "args", "with", "severity", "FATAL", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L994-L996
234,292
abseil/abseil-py
absl/logging/__init__.py
ABSLLogger.warn
def warn(self, msg, *args, **kwargs): """Logs 'msg % args' with severity 'WARN'.""" if six.PY3: warnings.warn("The 'warn' method is deprecated, use 'warning' instead", DeprecationWarning, 2) self.log(logging.WARN, msg, *args, **kwargs)
python
def warn(self, msg, *args, **kwargs): if six.PY3: warnings.warn("The 'warn' method is deprecated, use 'warning' instead", DeprecationWarning, 2) self.log(logging.WARN, msg, *args, **kwargs)
[ "def", "warn", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY3", ":", "warnings", ".", "warn", "(", "\"The 'warn' method is deprecated, use 'warning' instead\"", ",", "DeprecationWarning", ",", "2", ")", ...
Logs 'msg % args' with severity 'WARN'.
[ "Logs", "msg", "%", "args", "with", "severity", "WARN", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1002-L1007
234,293
abseil/abseil-py
absl/logging/__init__.py
ABSLLogger.log
def log(self, level, msg, *args, **kwargs): """Logs a message at a cetain level substituting in the supplied arguments. This method behaves differently in python and c++ modes. Args: level: int, the standard logging level at which to log the message. msg: str, the text of the message to log. *args: The arguments to substitute in the message. **kwargs: The keyword arguments to substitute in the message. """ if level >= logging.FATAL: # Add property to the LogRecord created by this logger. # This will be used by the ABSLHandler to determine whether it should # treat CRITICAL/FATAL logs as really FATAL. extra = kwargs.setdefault('extra', {}) extra[_ABSL_LOG_FATAL] = True super(ABSLLogger, self).log(level, msg, *args, **kwargs)
python
def log(self, level, msg, *args, **kwargs): if level >= logging.FATAL: # Add property to the LogRecord created by this logger. # This will be used by the ABSLHandler to determine whether it should # treat CRITICAL/FATAL logs as really FATAL. extra = kwargs.setdefault('extra', {}) extra[_ABSL_LOG_FATAL] = True super(ABSLLogger, self).log(level, msg, *args, **kwargs)
[ "def", "log", "(", "self", ",", "level", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "level", ">=", "logging", ".", "FATAL", ":", "# Add property to the LogRecord created by this logger.", "# This will be used by the ABSLHandler to determi...
Logs a message at a cetain level substituting in the supplied arguments. This method behaves differently in python and c++ modes. Args: level: int, the standard logging level at which to log the message. msg: str, the text of the message to log. *args: The arguments to substitute in the message. **kwargs: The keyword arguments to substitute in the message.
[ "Logs", "a", "message", "at", "a", "cetain", "level", "substituting", "in", "the", "supplied", "arguments", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1021-L1038
234,294
abseil/abseil-py
absl/logging/__init__.py
ABSLLogger.register_frame_to_skip
def register_frame_to_skip(cls, file_name, function_name, line_number=None): """Registers a function name to skip when walking the stack. The ABSLLogger sometimes skips method calls on the stack to make the log messages meaningful in their appropriate context. This method registers a function from a particular file as one which should be skipped. Args: file_name: str, the name of the file that contains the function. function_name: str, the name of the function to skip. line_number: int, if provided, only the function with this starting line number will be skipped. Otherwise, all functions with the same name in the file will be skipped. """ if line_number is not None: cls._frames_to_skip.add((file_name, function_name, line_number)) else: cls._frames_to_skip.add((file_name, function_name))
python
def register_frame_to_skip(cls, file_name, function_name, line_number=None): if line_number is not None: cls._frames_to_skip.add((file_name, function_name, line_number)) else: cls._frames_to_skip.add((file_name, function_name))
[ "def", "register_frame_to_skip", "(", "cls", ",", "file_name", ",", "function_name", ",", "line_number", "=", "None", ")", ":", "if", "line_number", "is", "not", "None", ":", "cls", ".", "_frames_to_skip", ".", "add", "(", "(", "file_name", ",", "function_na...
Registers a function name to skip when walking the stack. The ABSLLogger sometimes skips method calls on the stack to make the log messages meaningful in their appropriate context. This method registers a function from a particular file as one which should be skipped. Args: file_name: str, the name of the file that contains the function. function_name: str, the name of the function to skip. line_number: int, if provided, only the function with this starting line number will be skipped. Otherwise, all functions with the same name in the file will be skipped.
[ "Registers", "a", "function", "name", "to", "skip", "when", "walking", "the", "stack", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1058-L1076
234,295
abseil/abseil-py
absl/flags/argparse_flags.py
_is_undefok
def _is_undefok(arg, undefok_names): """Returns whether we can ignore arg based on a set of undefok flag names.""" if not arg.startswith('-'): return False if arg.startswith('--'): arg_without_dash = arg[2:] else: arg_without_dash = arg[1:] if '=' in arg_without_dash: name, _ = arg_without_dash.split('=', 1) else: name = arg_without_dash if name in undefok_names: return True return False
python
def _is_undefok(arg, undefok_names): if not arg.startswith('-'): return False if arg.startswith('--'): arg_without_dash = arg[2:] else: arg_without_dash = arg[1:] if '=' in arg_without_dash: name, _ = arg_without_dash.split('=', 1) else: name = arg_without_dash if name in undefok_names: return True return False
[ "def", "_is_undefok", "(", "arg", ",", "undefok_names", ")", ":", "if", "not", "arg", ".", "startswith", "(", "'-'", ")", ":", "return", "False", "if", "arg", ".", "startswith", "(", "'--'", ")", ":", "arg_without_dash", "=", "arg", "[", "2", ":", "]...
Returns whether we can ignore arg based on a set of undefok flag names.
[ "Returns", "whether", "we", "can", "ignore", "arg", "based", "on", "a", "set", "of", "undefok", "flag", "names", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/argparse_flags.py#L358-L372
234,296
abseil/abseil-py
absl/flags/argparse_flags.py
ArgumentParser._define_absl_flags
def _define_absl_flags(self, absl_flags): """Defines flags from absl_flags.""" key_flags = set(absl_flags.get_key_flags_for_module(sys.argv[0])) for name in absl_flags: if name in _BUILT_IN_FLAGS: # Do not inherit built-in flags. continue flag_instance = absl_flags[name] # Each flags with short_name appears in FLAGS twice, so only define # when the dictionary key is equal to the regular name. if name == flag_instance.name: # Suppress the flag in the help short message if it's not a main # module's key flag. suppress = flag_instance not in key_flags self._define_absl_flag(flag_instance, suppress)
python
def _define_absl_flags(self, absl_flags): key_flags = set(absl_flags.get_key_flags_for_module(sys.argv[0])) for name in absl_flags: if name in _BUILT_IN_FLAGS: # Do not inherit built-in flags. continue flag_instance = absl_flags[name] # Each flags with short_name appears in FLAGS twice, so only define # when the dictionary key is equal to the regular name. if name == flag_instance.name: # Suppress the flag in the help short message if it's not a main # module's key flag. suppress = flag_instance not in key_flags self._define_absl_flag(flag_instance, suppress)
[ "def", "_define_absl_flags", "(", "self", ",", "absl_flags", ")", ":", "key_flags", "=", "set", "(", "absl_flags", ".", "get_key_flags_for_module", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "for", "name", "in", "absl_flags", ":", "if", "name", "i...
Defines flags from absl_flags.
[ "Defines", "flags", "from", "absl_flags", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/argparse_flags.py#L196-L210
234,297
abseil/abseil-py
absl/flags/argparse_flags.py
ArgumentParser._define_absl_flag
def _define_absl_flag(self, flag_instance, suppress): """Defines a flag from the flag_instance.""" flag_name = flag_instance.name short_name = flag_instance.short_name argument_names = ['--' + flag_name] if short_name: argument_names.insert(0, '-' + short_name) if suppress: helptext = argparse.SUPPRESS else: # argparse help string uses %-formatting. Escape the literal %'s. helptext = flag_instance.help.replace('%', '%%') if flag_instance.boolean: # Only add the `no` form to the long name. argument_names.append('--no' + flag_name) self.add_argument( *argument_names, action=_BooleanFlagAction, help=helptext, metavar=flag_instance.name.upper(), flag_instance=flag_instance) else: self.add_argument( *argument_names, action=_FlagAction, help=helptext, metavar=flag_instance.name.upper(), flag_instance=flag_instance)
python
def _define_absl_flag(self, flag_instance, suppress): flag_name = flag_instance.name short_name = flag_instance.short_name argument_names = ['--' + flag_name] if short_name: argument_names.insert(0, '-' + short_name) if suppress: helptext = argparse.SUPPRESS else: # argparse help string uses %-formatting. Escape the literal %'s. helptext = flag_instance.help.replace('%', '%%') if flag_instance.boolean: # Only add the `no` form to the long name. argument_names.append('--no' + flag_name) self.add_argument( *argument_names, action=_BooleanFlagAction, help=helptext, metavar=flag_instance.name.upper(), flag_instance=flag_instance) else: self.add_argument( *argument_names, action=_FlagAction, help=helptext, metavar=flag_instance.name.upper(), flag_instance=flag_instance)
[ "def", "_define_absl_flag", "(", "self", ",", "flag_instance", ",", "suppress", ")", ":", "flag_name", "=", "flag_instance", ".", "name", "short_name", "=", "flag_instance", ".", "short_name", "argument_names", "=", "[", "'--'", "+", "flag_name", "]", "if", "s...
Defines a flag from the flag_instance.
[ "Defines", "a", "flag", "from", "the", "flag_instance", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/argparse_flags.py#L212-L235
234,298
abseil/abseil-py
absl/flags/_helpers.py
get_module_object_and_name
def get_module_object_and_name(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: _ModuleObjectAndName - pair of module object & module name. Returns (None, None) if the module could not be identified. """ name = globals_dict.get('__name__', None) module = sys.modules.get(name, None) # Pick a more informative name for the main module. return _ModuleObjectAndName(module, (sys.argv[0] if name == '__main__' else name))
python
def get_module_object_and_name(globals_dict): name = globals_dict.get('__name__', None) module = sys.modules.get(name, None) # Pick a more informative name for the main module. return _ModuleObjectAndName(module, (sys.argv[0] if name == '__main__' else name))
[ "def", "get_module_object_and_name", "(", "globals_dict", ")", ":", "name", "=", "globals_dict", ".", "get", "(", "'__name__'", ",", "None", ")", "module", "=", "sys", ".", "modules", ".", "get", "(", "name", ",", "None", ")", "# Pick a more informative name f...
Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: _ModuleObjectAndName - pair of module object & module name. Returns (None, None) if the module could not be identified.
[ "Returns", "the", "module", "that", "defines", "a", "global", "environment", "and", "its", "name", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L90-L105
234,299
abseil/abseil-py
absl/flags/_helpers.py
create_xml_dom_element
def create_xml_dom_element(doc, name, value): """Returns an XML DOM element with name and text value. Args: doc: minidom.Document, the DOM document it should create nodes from. name: str, the tag of XML element. value: object, whose string representation will be used as the value of the XML element. Illegal or highly discouraged xml 1.0 characters are stripped. Returns: An instance of minidom.Element. """ s = str_or_unicode(value) if six.PY2 and not isinstance(s, unicode): # Get a valid unicode string. s = s.decode('utf-8', 'ignore') if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. s = s.lower() # Remove illegal xml characters. s = _ILLEGAL_XML_CHARS_REGEX.sub(u'', s) e = doc.createElement(name) e.appendChild(doc.createTextNode(s)) return e
python
def create_xml_dom_element(doc, name, value): s = str_or_unicode(value) if six.PY2 and not isinstance(s, unicode): # Get a valid unicode string. s = s.decode('utf-8', 'ignore') if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. s = s.lower() # Remove illegal xml characters. s = _ILLEGAL_XML_CHARS_REGEX.sub(u'', s) e = doc.createElement(name) e.appendChild(doc.createTextNode(s)) return e
[ "def", "create_xml_dom_element", "(", "doc", ",", "name", ",", "value", ")", ":", "s", "=", "str_or_unicode", "(", "value", ")", "if", "six", ".", "PY2", "and", "not", "isinstance", "(", "s", ",", "unicode", ")", ":", "# Get a valid unicode string.", "s", ...
Returns an XML DOM element with name and text value. Args: doc: minidom.Document, the DOM document it should create nodes from. name: str, the tag of XML element. value: object, whose string representation will be used as the value of the XML element. Illegal or highly discouraged xml 1.0 characters are stripped. Returns: An instance of minidom.Element.
[ "Returns", "an", "XML", "DOM", "element", "with", "name", "and", "text", "value", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L161-L186