index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
730,475 | chromadb.api.types | __call__ | null | def __call__(self, input: D) -> Embeddings:
...
| (self, input: -D) -> List[Union[Sequence[float], Sequence[int]]] |
730,477 | chromadb.api.types | embed_with_retries | null | def embed_with_retries(self, input: D, **retry_kwargs: Dict) -> Embeddings:
return retry(**retry_kwargs)(self.__call__)(input)
| (self, input: -D, **retry_kwargs: Dict) -> List[Union[Sequence[float], Sequence[int]]] |
730,478 | chromadb | EphemeralClient |
Creates an in-memory instance of Chroma. This is useful for testing and
development, but not recommended for production use.
Args:
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
| def EphemeralClient(
settings: Optional[Settings] = None,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
) -> ClientAPI:
"""
Creates an in-memory instance of Chroma. This is useful for testing and
development, but not recommended for production use.
Args:
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
"""
if settings is None:
settings = Settings()
settings.is_persistent = False
# Make sure paramaters are the correct types -- users can pass anything.
tenant = str(tenant)
database = str(database)
return ClientCreator(settings=settings, tenant=tenant, database=database)
| (settings: Optional[chromadb.config.Settings] = None, tenant: str = 'default_tenant', database: str = 'default_database') -> chromadb.api.ClientAPI |
730,479 | chromadb.api.types | GetResult | null | class GetResult(TypedDict):
ids: List[ID]
embeddings: Optional[List[Embedding]]
documents: Optional[List[Document]]
uris: Optional[URIs]
data: Optional[Loadable]
metadatas: Optional[List[Metadata]]
| null |
730,480 | chromadb | HttpClient |
Creates a client that connects to a remote Chroma server. This supports
many clients connecting to the same server, and is the recommended way to
use Chroma in production.
Args:
host: The hostname of the Chroma server. Defaults to "localhost".
port: The port of the Chroma server. Defaults to "8000".
ssl: Whether to use SSL to connect to the Chroma server. Defaults to False.
headers: A dictionary of headers to send to the Chroma server. Defaults to {}.
settings: A dictionary of settings to communicate with the chroma server.
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
| def HttpClient(
host: str = "localhost",
port: int = 8000,
ssl: bool = False,
headers: Optional[Dict[str, str]] = None,
settings: Optional[Settings] = None,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
) -> ClientAPI:
"""
Creates a client that connects to a remote Chroma server. This supports
many clients connecting to the same server, and is the recommended way to
use Chroma in production.
Args:
host: The hostname of the Chroma server. Defaults to "localhost".
port: The port of the Chroma server. Defaults to "8000".
ssl: Whether to use SSL to connect to the Chroma server. Defaults to False.
headers: A dictionary of headers to send to the Chroma server. Defaults to {}.
settings: A dictionary of settings to communicate with the chroma server.
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
"""
if settings is None:
settings = Settings()
# Make sure paramaters are the correct types -- users can pass anything.
host = str(host)
port = int(port)
ssl = bool(ssl)
tenant = str(tenant)
database = str(database)
settings.chroma_api_impl = "chromadb.api.fastapi.FastAPI"
if settings.chroma_server_host and settings.chroma_server_host != host:
raise ValueError(
f"Chroma server host provided in settings[{settings.chroma_server_host}] is different to the one provided in HttpClient: [{host}]"
)
settings.chroma_server_host = host
if settings.chroma_server_http_port and settings.chroma_server_http_port != port:
raise ValueError(
f"Chroma server http port provided in settings[{settings.chroma_server_http_port}] is different to the one provided in HttpClient: [{port}]"
)
settings.chroma_server_http_port = port
settings.chroma_server_ssl_enabled = ssl
settings.chroma_server_headers = headers
return ClientCreator(tenant=tenant, database=database, settings=settings)
| (host: str = 'localhost', port: int = 8000, ssl: bool = False, headers: Optional[Dict[str, str]] = None, settings: Optional[chromadb.config.Settings] = None, tenant: str = 'default_tenant', database: str = 'default_database') -> chromadb.api.ClientAPI |
730,481 | chromadb | PersistentClient |
Creates a persistent instance of Chroma that saves to disk. This is useful for
testing and development, but not recommended for production use.
Args:
path: The directory to save Chroma's data to. Defaults to "./chroma".
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
| def PersistentClient(
path: str = "./chroma",
settings: Optional[Settings] = None,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
) -> ClientAPI:
"""
Creates a persistent instance of Chroma that saves to disk. This is useful for
testing and development, but not recommended for production use.
Args:
path: The directory to save Chroma's data to. Defaults to "./chroma".
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
"""
if settings is None:
settings = Settings()
settings.persist_directory = path
settings.is_persistent = True
# Make sure paramaters are the correct types -- users can pass anything.
tenant = str(tenant)
database = str(database)
return ClientCreator(tenant=tenant, database=database, settings=settings)
| (path: str = './chroma', settings: Optional[chromadb.config.Settings] = None, tenant: str = 'default_tenant', database: str = 'default_database') -> chromadb.api.ClientAPI |
730,482 | chromadb.api.types | QueryResult | null | class QueryResult(TypedDict):
ids: List[IDs]
embeddings: Optional[List[List[Embedding]]]
documents: Optional[List[List[Document]]]
uris: Optional[List[List[URI]]]
data: Optional[List[Loadable]]
metadatas: Optional[List[List[Metadata]]]
distances: Optional[List[List[float]]]
| null |
730,483 | chromadb.config | Settings | null | class Settings(BaseSettings): # type: ignore
# ==============
# Generic config
# ==============
environment: str = ""
# Can be "chromadb.api.segment.SegmentAPI" or "chromadb.api.fastapi.FastAPI"
chroma_api_impl: str = "chromadb.api.segment.SegmentAPI"
@validator("chroma_server_nofile", pre=True, always=True, allow_reuse=True)
def empty_str_to_none(cls, v: str) -> Optional[str]:
if type(v) is str and v.strip() == "":
return None
return v
chroma_server_nofile: Optional[int] = None
# the number of maximum threads to handle synchronous tasks in the FastAPI server
chroma_server_thread_pool_size: int = 40
# ==================
# Client-mode config
# ==================
tenant_id: str = "default"
topic_namespace: str = "default"
chroma_server_host: Optional[str] = None
chroma_server_headers: Optional[Dict[str, str]] = None
chroma_server_http_port: Optional[int] = None
chroma_server_ssl_enabled: Optional[bool] = False
chroma_server_ssl_verify: Optional[Union[bool, str]] = None
chroma_server_api_default_path: Optional[str] = "/api/v1"
# eg ["http://localhost:3000"]
chroma_server_cors_allow_origins: List[str] = []
# ==================
# Server config
# ==================
is_persistent: bool = False
persist_directory: str = "./chroma"
chroma_memory_limit_bytes: int = 0
chroma_segment_cache_policy: Optional[str] = None
allow_reset: bool = False
# ===========================
# {Client, Server} auth{n, z}
# ===========================
# The header to use for the token. Defaults to "Authorization".
chroma_auth_token_transport_header: Optional[str] = None
# ================
# Client auth{n,z}
# ================
# The provider for client auth. See chromadb/auth/__init__.py
chroma_client_auth_provider: Optional[str] = None
# If needed by the provider (e.g. BasicAuthClientProvider),
# the credentials to use.
chroma_client_auth_credentials: Optional[str] = None
# ================
# Server auth{n,z}
# ================
chroma_server_auth_ignore_paths: Dict[str, List[str]] = {
"/api/v1": ["GET"],
"/api/v1/heartbeat": ["GET"],
"/api/v1/version": ["GET"],
}
# Overwrite singleton tenant and database access from the auth provider
# if applicable. See chromadb/server/fastapi/__init__.py's
# authenticate_and_authorize_or_raise method.
chroma_overwrite_singleton_tenant_database_access_from_auth: bool = False
# ============
# Server authn
# ============
chroma_server_authn_provider: Optional[str] = None
# Only one of the below may be specified.
chroma_server_authn_credentials: Optional[str] = None
chroma_server_authn_credentials_file: Optional[str] = None
# ============
# Server authz
# ============
chroma_server_authz_provider: Optional[str] = None
# Only one of the below may be specified.
chroma_server_authz_config: Optional[str] = None
chroma_server_authz_config_file: Optional[str] = None
# =========
# Telemetry
# =========
chroma_product_telemetry_impl: str = \
"chromadb.telemetry.product.posthog.Posthog"
# Required for backwards compatibility
chroma_telemetry_impl: str = chroma_product_telemetry_impl
anonymized_telemetry: bool = True
chroma_otel_collection_endpoint: Optional[str] = ""
chroma_otel_service_name: Optional[str] = "chromadb"
chroma_otel_collection_headers: Dict[str, str] = {}
chroma_otel_granularity: Optional[str] = None
# ==========
# Migrations
# ==========
migrations: Literal["none", "validate", "apply"] = "apply"
# you cannot change the hash_algorithm after migrations have already
# been applied once this is intended to be a first-time setup configuration
migrations_hash_algorithm: Literal["md5", "sha256"] = "md5"
# ==================
# Distributed Chroma
# ==================
chroma_segment_directory_impl: str = "chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory"
chroma_memberlist_provider_impl: str = "chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider"
worker_memberlist_name: str = "query-service-memberlist"
chroma_coordinator_host = "localhost"
# TODO this is the sysdb port. Should probably rename it.
chroma_server_grpc_port: Optional[int] = None
chroma_sysdb_impl: str = "chromadb.db.impl.sqlite.SqliteDB"
chroma_producer_impl: str = "chromadb.db.impl.sqlite.SqliteDB"
chroma_consumer_impl: str = "chromadb.db.impl.sqlite.SqliteDB"
chroma_segment_manager_impl: str = (
"chromadb.segment.impl.manager.local.LocalSegmentManager"
)
chroma_logservice_host = "localhost"
chroma_logservice_port = 50052
chroma_quota_provider_impl: Optional[str] = None
chroma_rate_limiting_provider_impl: Optional[str] = None
# ======
# Legacy
# ======
chroma_db_impl: Optional[str] = None
chroma_collection_assignment_policy_impl: str = (
"chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy"
)
# =======
# Methods
# =======
def require(self, key: str) -> Any:
"""Return the value of a required config key, or raise an exception if it is not
set"""
val = self[key]
if val is None:
raise ValueError(f"Missing required config value '{key}'")
return val
def __getitem__(self, key: str) -> Any:
val = getattr(self, key)
# Error on legacy config values
if isinstance(val, str) and val in _legacy_config_values:
raise ValueError(LEGACY_ERROR)
return val
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
| (_env_file: Union[str, os.PathLike, List[Union[str, os.PathLike]], Tuple[Union[str, os.PathLike], ...], NoneType] = '<object object at 0x7fd50aaedf00>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Union[str, os.PathLike, NoneType] = None, *, environment: str = '', chroma_api_impl: str = 'chromadb.api.segment.SegmentAPI', chroma_server_nofile: Optional[int] = None, chroma_server_thread_pool_size: int = 40, tenant_id: str = 'default', topic_namespace: str = 'default', chroma_server_host: Optional[str] = None, chroma_server_headers: Optional[Dict[str, str]] = None, chroma_server_http_port: Optional[int] = None, chroma_server_ssl_enabled: Optional[bool] = False, chroma_server_ssl_verify: Union[bool, str, NoneType] = None, chroma_server_api_default_path: Optional[str] = '/api/v1', chroma_server_cors_allow_origins: List[str] = [], is_persistent: bool = False, persist_directory: str = './chroma', chroma_memory_limit_bytes: int = 0, chroma_segment_cache_policy: Optional[str] = None, allow_reset: bool = False, chroma_auth_token_transport_header: Optional[str] = None, chroma_client_auth_provider: Optional[str] = None, chroma_client_auth_credentials: Optional[str] = None, chroma_server_auth_ignore_paths: Dict[str, List[str]] = {'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth: bool = False, chroma_server_authn_provider: Optional[str] = None, chroma_server_authn_credentials: Optional[str] = None, chroma_server_authn_credentials_file: Optional[str] = None, chroma_server_authz_provider: Optional[str] = None, chroma_server_authz_config: Optional[str] = None, chroma_server_authz_config_file: Optional[str] = None, chroma_product_telemetry_impl: str = 'chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl: str = 'chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry: bool = True, chroma_otel_collection_endpoint: Optional[str] = '', chroma_otel_service_name: Optional[str] = 'chromadb', chroma_otel_collection_headers: Dict[str, str] = {}, chroma_otel_granularity: Optional[str] = None, migrations: Literal['none', 'validate', 'apply'] = 'apply', migrations_hash_algorithm: Literal['md5', 'sha256'] = 'md5', chroma_segment_directory_impl: str = 'chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl: str = 'chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name: str = 'query-service-memberlist', chroma_server_grpc_port: Optional[int] = None, chroma_sysdb_impl: str = 'chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl: str = 'chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl: str = 'chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl: str = 'chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl: Optional[str] = None, chroma_rate_limiting_provider_impl: Optional[str] = None, chroma_db_impl: Optional[str] = None, chroma_collection_assignment_policy_impl: str = 'chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host: str = 'localhost', chroma_logservice_host: str = 'localhost', chroma_logservice_port: int = 50052) -> None |
730,485 | chromadb.config | __getitem__ | null | def __getitem__(self, key: str) -> Any:
val = getattr(self, key)
# Error on legacy config values
if isinstance(val, str) and val in _legacy_config_values:
raise ValueError(LEGACY_ERROR)
return val
| (self, key: str) -> Any |
730,487 | pydantic.v1.env_settings | __init__ | null | def __init__(
__pydantic_self__,
_env_file: Optional[DotenvType] = env_file_sentinel,
_env_file_encoding: Optional[str] = None,
_env_nested_delimiter: Optional[str] = None,
_secrets_dir: Optional[StrPath] = None,
**values: Any,
) -> None:
# Uses something other than `self` the first arg to allow "self" as a settable attribute
super().__init__(
**__pydantic_self__._build_values(
values,
_env_file=_env_file,
_env_file_encoding=_env_file_encoding,
_env_nested_delimiter=_env_nested_delimiter,
_secrets_dir=_secrets_dir,
)
)
| (__pydantic_self__, _env_file: Union[str, os.PathLike, List[Union[str, os.PathLike]], Tuple[Union[str, os.PathLike], ...], NoneType] = '<object object at 0x7fd50aaedf00>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Union[str, os.PathLike, NoneType] = None, **values: Any) -> NoneType |
730,499 | pydantic.v1.env_settings | _build_values | null | def _build_values(
self,
init_kwargs: Dict[str, Any],
_env_file: Optional[DotenvType] = None,
_env_file_encoding: Optional[str] = None,
_env_nested_delimiter: Optional[str] = None,
_secrets_dir: Optional[StrPath] = None,
) -> Dict[str, Any]:
# Configure built-in sources
init_settings = InitSettingsSource(init_kwargs=init_kwargs)
env_settings = EnvSettingsSource(
env_file=(_env_file if _env_file != env_file_sentinel else self.__config__.env_file),
env_file_encoding=(
_env_file_encoding if _env_file_encoding is not None else self.__config__.env_file_encoding
),
env_nested_delimiter=(
_env_nested_delimiter if _env_nested_delimiter is not None else self.__config__.env_nested_delimiter
),
env_prefix_len=len(self.__config__.env_prefix),
)
file_secret_settings = SecretsSettingsSource(secrets_dir=_secrets_dir or self.__config__.secrets_dir)
# Provide a hook to set built-in sources priority and add / remove sources
sources = self.__config__.customise_sources(
init_settings=init_settings, env_settings=env_settings, file_secret_settings=file_secret_settings
)
if sources:
return deep_update(*reversed([source(self) for source in sources]))
else:
# no one should mean to do this, but I think returning an empty dict is marginally preferable
# to an informative error and much better than a confusing error
return {}
| (self, init_kwargs: Dict[str, Any], _env_file: Union[str, os.PathLike, List[Union[str, os.PathLike]], Tuple[Union[str, os.PathLike], ...], NoneType] = None, _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Union[str, os.PathLike, NoneType] = None) -> Dict[str, Any] |
730,507 | chromadb.config | require | Return the value of a required config key, or raise an exception if it is not
set | def require(self, key: str) -> Any:
"""Return the value of a required config key, or raise an exception if it is not
set"""
val = self[key]
if val is None:
raise ValueError(f"Missing required config value '{key}'")
return val
| (self, key: str) -> Any |
730,508 | chromadb.auth.token_authn | TokenTransportHeader |
Accceptable token transport headers.
| class TokenTransportHeader(Enum):
"""
Accceptable token transport headers.
"""
# I don't love having this enum here -- it's weird to have an enum
# for just two values and it's weird to have users pass X_CHROMA_TOKEN
# to configure "x-chroma-token". But I also like having a single source
# of truth, so 🤷🏻♂️
AUTHORIZATION = "Authorization"
X_CHROMA_TOKEN = "X-Chroma-Token"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
730,513 | chromadb | configure | Override Chroma's default settings, environment variables or .env files | def configure(**kwargs) -> None: # type: ignore
"""Override Chroma's default settings, environment variables or .env files"""
global __settings
__settings = chromadb.config.Settings(**kwargs)
| (**kwargs) -> NoneType |
730,515 | chromadb | get_settings | null | def get_settings() -> Settings:
return __settings
| () -> chromadb.config.Settings |
730,526 | sphinx_adc_theme | get_html_theme_path | Return list of HTML theme paths. | def get_html_theme_path():
"""Return list of HTML theme paths."""
return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
| () |
730,527 | sphinx_adc_theme | get_theme_version | Return the theme version | def get_theme_version():
"""Return the theme version"""
return __version__
| () |
730,529 | sphinx_adc_theme | setup | null | def setup(app):
app.connect('html-page-context', update_context)
app.add_html_theme('sphinx_adc_theme', get_html_theme_path())
return {'version': __version__,
'parallel_read_safe': True}
| (app) |
730,530 | sphinx_adc_theme | update_context | null | def update_context(app, pagename, templatename, context, doctree):
context['adc_theme_version'] = __version__
| (app, pagename, templatename, context, doctree) |
730,531 | pickledb_ujson | PickleDB | null | class PickleDB:
key_string_error = TypeError("Key/name must be a string!")
def __init__(self, location, auto_dump, sig):
"""Creates a database object and loads the data from the location path.
If the file does not exist it will be created on the first update.
"""
self.load(location, auto_dump)
self.dthread = None
if sig:
self.set_sigterm_handler()
def __getitem__(self, item):
"""Syntax sugar for get()"""
return self.get(item)
def __setitem__(self, key, value):
"""Sytax sugar for set()"""
return self.set(key, value)
def __delitem__(self, key):
"""Sytax sugar for rem()"""
return self.rem(key)
def set_sigterm_handler(self):
"""Assigns sigterm_handler for graceful shutdown during dump()"""
def sigterm_handler():
if self.dthread is not None:
self.dthread.join()
sys_exit(0)
signal(SIGTERM, sigterm_handler)
def load(self, location, auto_dump):
"""Loads, reloads or changes the path to the db file"""
location = path.expanduser(location)
self.loco = location
self.auto_dump = auto_dump
if path.exists(location):
self._loaddb()
else:
self.db = {}
return True
def dump(self):
"""Force dump memory db to file"""
dump(self.db, open(self.loco, "w"))
self.dthread = Thread(target=dump, args=(self.db, open(self.loco, "w")))
self.dthread.start()
self.dthread.join()
return True
def _loaddb(self):
"""Load or reload the json info from the file"""
try:
self.db = load(open(self.loco))
except ValueError:
if stat(self.loco).st_size == 0: # Error raised because file is empty
self.db = {}
else:
raise # File is not empty, avoid overwriting it
def _autodumpdb(self):
"""Write/save the json dump into the file if auto_dump is enabled"""
if self.auto_dump:
self.dump()
def set(self, key, value):
"""Set the str value of a key"""
if isinstance(key, str):
self.db[key] = value
self._autodumpdb()
return True
else:
raise self.key_string_error
def get(self, key):
"""Get the value of a key"""
try:
return self.db[key]
except KeyError:
return False
def getall(self):
"""Return a list of all keys in db"""
return self.db.keys()
def exists(self, key):
"""Return True if key exists in db, return False if not"""
return key in self.db
def rem(self, key):
"""Delete a key"""
if not key in self.db: # return False instead of an exception
return False
del self.db[key]
self._autodumpdb()
return True
def totalkeys(self, name=None):
"""Get a total number of keys, lists, and dicts inside the db"""
if name is None:
total = len(self.db)
return total
else:
total = len(self.db[name])
return total
def append(self, key, more):
"""Add more to a key's value"""
tmp = self.db[key]
self.db[key] = tmp + more
self._autodumpdb()
return True
def lcreate(self, name):
"""Create a list, name must be str"""
if isinstance(name, str):
self.db[name] = []
self._autodumpdb()
return True
else:
raise self.key_string_error
def ladd(self, name, value):
"""Add a value to a list"""
self.db[name].append(value)
self._autodumpdb()
return True
def lextend(self, name, seq):
"""Extend a list with a sequence"""
self.db[name].extend(seq)
self._autodumpdb()
return True
def lgetall(self, name):
"""Return all values in a list"""
return self.db[name]
def lget(self, name, pos):
"""Return one value in a list"""
return self.db[name][pos]
def lrange(self, name, start=None, end=None):
"""Return range of values in a list"""
return self.db[name][start:end]
def lremlist(self, name):
"""Remove a list and all of its values"""
number = len(self.db[name])
del self.db[name]
self._autodumpdb()
return number
def lremvalue(self, name, value):
"""Remove a value from a certain list"""
self.db[name].remove(value)
self._autodumpdb()
return True
def lpop(self, name, pos):
"""Remove one value in a list"""
value = self.db[name][pos]
del self.db[name][pos]
self._autodumpdb()
return value
def llen(self, name):
"""Returns the length of the list"""
return len(self.db[name])
def lappend(self, name, pos, more):
"""Add more to a value in a list"""
tmp = self.db[name][pos]
self.db[name][pos] = tmp + more
self._autodumpdb()
return True
def lexists(self, name, value):
"""Determine if a value exists in a list"""
return value in self.db[name]
def dcreate(self, name):
"""Create a dict, name must be str"""
if isinstance(name, str):
self.db[name] = {}
self._autodumpdb()
return True
else:
raise self.key_string_error
def dadd(self, name, pair):
"""Add a key-value pair to a dict, "pair" is a tuple"""
self.db[name][pair[0]] = pair[1]
self._autodumpdb()
return True
def dget(self, name, key):
"""Return the value for a key in a dict"""
return self.db[name][key]
def dgetall(self, name):
"""Return all key-value pairs from a dict"""
return self.db[name]
def drem(self, name):
"""Remove a dict and all of its pairs"""
del self.db[name]
self._autodumpdb()
return True
def dpop(self, name, key):
"""Remove one key-value pair in a dict"""
value = self.db[name][key]
del self.db[name][key]
self._autodumpdb()
return value
def dkeys(self, name):
"""Return all the keys for a dict"""
return self.db[name].keys()
def dvals(self, name):
"""Return all the values for a dict"""
return self.db[name].values()
def dexists(self, name, key):
"""Determine if a key exists or not in a dict"""
return key in self.db[name]
def dmerge(self, name1, name2):
"""Merge two dicts together into name1"""
first = self.db[name1]
second = self.db[name2]
first.update(second)
self._autodumpdb()
return True
def deldb(self):
"""Delete everything from the database"""
self.db = {}
self._autodumpdb()
return True
| (location, auto_dump, sig) |
730,532 | pickledb_ujson | __delitem__ | Sytax sugar for rem() | def __delitem__(self, key):
"""Sytax sugar for rem()"""
return self.rem(key)
| (self, key) |
730,533 | pickledb_ujson | __getitem__ | Syntax sugar for get() | def __getitem__(self, item):
"""Syntax sugar for get()"""
return self.get(item)
| (self, item) |
730,534 | pickledb_ujson | __init__ | Creates a database object and loads the data from the location path.
If the file does not exist it will be created on the first update.
| def __init__(self, location, auto_dump, sig):
"""Creates a database object and loads the data from the location path.
If the file does not exist it will be created on the first update.
"""
self.load(location, auto_dump)
self.dthread = None
if sig:
self.set_sigterm_handler()
| (self, location, auto_dump, sig) |
730,535 | pickledb_ujson | __setitem__ | Sytax sugar for set() | def __setitem__(self, key, value):
"""Sytax sugar for set()"""
return self.set(key, value)
| (self, key, value) |
730,536 | pickledb_ujson | _autodumpdb | Write/save the json dump into the file if auto_dump is enabled | def _autodumpdb(self):
"""Write/save the json dump into the file if auto_dump is enabled"""
if self.auto_dump:
self.dump()
| (self) |
730,537 | pickledb_ujson | _loaddb | Load or reload the json info from the file | def _loaddb(self):
"""Load or reload the json info from the file"""
try:
self.db = load(open(self.loco))
except ValueError:
if stat(self.loco).st_size == 0: # Error raised because file is empty
self.db = {}
else:
raise # File is not empty, avoid overwriting it
| (self) |
730,538 | pickledb_ujson | append | Add more to a key's value | def append(self, key, more):
"""Add more to a key's value"""
tmp = self.db[key]
self.db[key] = tmp + more
self._autodumpdb()
return True
| (self, key, more) |
730,539 | pickledb_ujson | dadd | Add a key-value pair to a dict, "pair" is a tuple | def dadd(self, name, pair):
"""Add a key-value pair to a dict, "pair" is a tuple"""
self.db[name][pair[0]] = pair[1]
self._autodumpdb()
return True
| (self, name, pair) |
730,540 | pickledb_ujson | dcreate | Create a dict, name must be str | def dcreate(self, name):
"""Create a dict, name must be str"""
if isinstance(name, str):
self.db[name] = {}
self._autodumpdb()
return True
else:
raise self.key_string_error
| (self, name) |
730,541 | pickledb_ujson | deldb | Delete everything from the database | def deldb(self):
"""Delete everything from the database"""
self.db = {}
self._autodumpdb()
return True
| (self) |
730,542 | pickledb_ujson | dexists | Determine if a key exists or not in a dict | def dexists(self, name, key):
"""Determine if a key exists or not in a dict"""
return key in self.db[name]
| (self, name, key) |
730,543 | pickledb_ujson | dget | Return the value for a key in a dict | def dget(self, name, key):
"""Return the value for a key in a dict"""
return self.db[name][key]
| (self, name, key) |
730,544 | pickledb_ujson | dgetall | Return all key-value pairs from a dict | def dgetall(self, name):
"""Return all key-value pairs from a dict"""
return self.db[name]
| (self, name) |
730,545 | pickledb_ujson | dkeys | Return all the keys for a dict | def dkeys(self, name):
"""Return all the keys for a dict"""
return self.db[name].keys()
| (self, name) |
730,546 | pickledb_ujson | dmerge | Merge two dicts together into name1 | def dmerge(self, name1, name2):
"""Merge two dicts together into name1"""
first = self.db[name1]
second = self.db[name2]
first.update(second)
self._autodumpdb()
return True
| (self, name1, name2) |
730,547 | pickledb_ujson | dpop | Remove one key-value pair in a dict | def dpop(self, name, key):
"""Remove one key-value pair in a dict"""
value = self.db[name][key]
del self.db[name][key]
self._autodumpdb()
return value
| (self, name, key) |
730,548 | pickledb_ujson | drem | Remove a dict and all of its pairs | def drem(self, name):
"""Remove a dict and all of its pairs"""
del self.db[name]
self._autodumpdb()
return True
| (self, name) |
730,549 | pickledb_ujson | dump | Force dump memory db to file | def dump(self):
"""Force dump memory db to file"""
dump(self.db, open(self.loco, "w"))
self.dthread = Thread(target=dump, args=(self.db, open(self.loco, "w")))
self.dthread.start()
self.dthread.join()
return True
| (self) |
730,550 | pickledb_ujson | dvals | Return all the values for a dict | def dvals(self, name):
"""Return all the values for a dict"""
return self.db[name].values()
| (self, name) |
730,551 | pickledb_ujson | exists | Return True if key exists in db, return False if not | def exists(self, key):
"""Return True if key exists in db, return False if not"""
return key in self.db
| (self, key) |
730,552 | pickledb_ujson | get | Get the value of a key | def get(self, key):
"""Get the value of a key"""
try:
return self.db[key]
except KeyError:
return False
| (self, key) |
730,553 | pickledb_ujson | getall | Return a list of all keys in db | def getall(self):
"""Return a list of all keys in db"""
return self.db.keys()
| (self) |
730,554 | pickledb_ujson | ladd | Add a value to a list | def ladd(self, name, value):
"""Add a value to a list"""
self.db[name].append(value)
self._autodumpdb()
return True
| (self, name, value) |
730,555 | pickledb_ujson | lappend | Add more to a value in a list | def lappend(self, name, pos, more):
"""Add more to a value in a list"""
tmp = self.db[name][pos]
self.db[name][pos] = tmp + more
self._autodumpdb()
return True
| (self, name, pos, more) |
730,556 | pickledb_ujson | lcreate | Create a list, name must be str | def lcreate(self, name):
"""Create a list, name must be str"""
if isinstance(name, str):
self.db[name] = []
self._autodumpdb()
return True
else:
raise self.key_string_error
| (self, name) |
730,557 | pickledb_ujson | lexists | Determine if a value exists in a list | def lexists(self, name, value):
"""Determine if a value exists in a list"""
return value in self.db[name]
| (self, name, value) |
730,558 | pickledb_ujson | lextend | Extend a list with a sequence | def lextend(self, name, seq):
"""Extend a list with a sequence"""
self.db[name].extend(seq)
self._autodumpdb()
return True
| (self, name, seq) |
730,559 | pickledb_ujson | lget | Return one value in a list | def lget(self, name, pos):
"""Return one value in a list"""
return self.db[name][pos]
| (self, name, pos) |
730,560 | pickledb_ujson | lgetall | Return all values in a list | def lgetall(self, name):
"""Return all values in a list"""
return self.db[name]
| (self, name) |
730,561 | pickledb_ujson | llen | Returns the length of the list | def llen(self, name):
"""Returns the length of the list"""
return len(self.db[name])
| (self, name) |
730,562 | pickledb_ujson | load | Loads, reloads or changes the path to the db file | def load(self, location, auto_dump):
"""Loads, reloads or changes the path to the db file"""
location = path.expanduser(location)
self.loco = location
self.auto_dump = auto_dump
if path.exists(location):
self._loaddb()
else:
self.db = {}
return True
| (self, location, auto_dump) |
730,563 | pickledb_ujson | lpop | Remove one value in a list | def lpop(self, name, pos):
"""Remove one value in a list"""
value = self.db[name][pos]
del self.db[name][pos]
self._autodumpdb()
return value
| (self, name, pos) |
730,564 | pickledb_ujson | lrange | Return range of values in a list | def lrange(self, name, start=None, end=None):
"""Return range of values in a list"""
return self.db[name][start:end]
| (self, name, start=None, end=None) |
730,565 | pickledb_ujson | lremlist | Remove a list and all of its values | def lremlist(self, name):
"""Remove a list and all of its values"""
number = len(self.db[name])
del self.db[name]
self._autodumpdb()
return number
| (self, name) |
730,566 | pickledb_ujson | lremvalue | Remove a value from a certain list | def lremvalue(self, name, value):
"""Remove a value from a certain list"""
self.db[name].remove(value)
self._autodumpdb()
return True
| (self, name, value) |
730,567 | pickledb_ujson | rem | Delete a key | def rem(self, key):
"""Delete a key"""
if not key in self.db: # return False instead of an exception
return False
del self.db[key]
self._autodumpdb()
return True
| (self, key) |
730,568 | pickledb_ujson | set | Set the str value of a key | def set(self, key, value):
"""Set the str value of a key"""
if isinstance(key, str):
self.db[key] = value
self._autodumpdb()
return True
else:
raise self.key_string_error
| (self, key, value) |
730,569 | pickledb_ujson | set_sigterm_handler | Assigns sigterm_handler for graceful shutdown during dump() | def set_sigterm_handler(self):
"""Assigns sigterm_handler for graceful shutdown during dump()"""
def sigterm_handler():
if self.dthread is not None:
self.dthread.join()
sys_exit(0)
signal(SIGTERM, sigterm_handler)
| (self) |
730,570 | pickledb_ujson | totalkeys | Get a total number of keys, lists, and dicts inside the db | def totalkeys(self, name=None):
"""Get a total number of keys, lists, and dicts inside the db"""
if name is None:
total = len(self.db)
return total
else:
total = len(self.db[name])
return total
| (self, name=None) |
730,591 | pickledb_ujson | load | Return a pickledb object. location is the path to the json file. | def load(location, auto_dump, sig=True):
"""Return a pickledb object. location is the path to the json file."""
return PickleDB(location, auto_dump, sig)
| (location, auto_dump, sig=True) |
730,593 | signal | signal | Set the action for the given signal.
The action can be SIG_DFL, SIG_IGN, or a callable Python object.
The previous action is returned. See getsignal() for possible return values.
*** IMPORTANT NOTICE ***
A signal handler function is called with two arguments:
the first is the signal number, the second is the interrupted stack frame. | @_wraps(_signal.signal)
def signal(signalnum, handler):
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
return _int_to_enum(handler, Handlers)
| (signalnum, handler) |
Subsets and Splits