### Install Dependencies and Run Tests with uv and tox Source: https://github.com/dahlia/wikidata/blob/main/CONTRIBUTING.rst This snippet shows how to synchronize project dependencies using 'uv' and then execute the test suite across various Python environments using 'tox'. It assumes 'uv' is installed and demonstrates the basic commands for setup and execution. ```shell uv sync --extra tests uv run tox ``` -------------------------------- ### Perform linting with flake8 Source: https://github.com/dahlia/wikidata/blob/main/CONTRIBUTING.rst Demonstrates the command to run 'flake8' for code linting. This checks the codebase for style guide violations and potential errors, promoting code quality and consistency. ```shell uv run flake8 ``` -------------------------------- ### Synchronize Dependencies with uv Source: https://github.com/dahlia/wikidata/blob/main/docs/contributing.md Installs and synchronizes project dependencies, including testing-related ones, using the uv package manager. This is a prerequisite for running tests and other development tasks. ```shell uv sync --extra tests ``` -------------------------------- ### Run tox tests skipping missing interpreters Source: https://github.com/dahlia/wikidata/blob/main/CONTRIBUTING.rst Demonstrates how to run tests using 'tox' while skipping any Python interpreters that are not currently installed on the system. This is useful for environments where not all supported Python versions are available. ```shell uv run tox --skip-missing-interpreters ``` -------------------------------- ### Python Wikidata Entity Property and Image Handling Source: https://github.com/dahlia/wikidata/blob/main/README.rst Illustrates how to get a specific property (like 'P18' for image) and access it from an entity object. It further shows how to retrieve image-specific details such as resolution and URL. Dependencies: 'wikidata' library. ```python from wikidata.client import Client client = Client() entity = client.get('Q20145', load=True) image_prop = client.get('P18') image = entity[image_prop] print(image) print(image.image_resolution) print(image.image_url) ``` -------------------------------- ### Get Entity and Calculate Age (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Retrieves an entity, accesses its death date and birth date properties, and calculates the age in years. Assumes 'client' and 'einstein' objects are pre-configured. ```python from wikidata.client import Client # Assuming 'client' and 'einstein' are pre-configured # birth_date = ... # P570 is "date of death" death_prop = client.get('P570') death_date = einstein[death_prop] print(death_date) # 1955-04-18 # Calculate age age = (death_date - birth_date).days // 365 print(f"Age: {age} years") ``` -------------------------------- ### ProxyCachePolicy Get Method Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/cache.md Retrieves a cached value using its key. If the key does not exist in the cache, it returns None. The key is expected to be of type CacheKey. ```python3 def get(key: CacheKey) -> CacheValue | None Look up a cached value by its `key`. * **Parameters:** **key** (CacheKey) – The key string to look up a cached value. * **Returns:** The cached value if it exists. `None` if there’s no such `key`. * **Return type:** Optional[CacheValue] ``` -------------------------------- ### Get Wikidata Entity Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/client.md Retrieves a Wikidata entity by its ID, with options for eager or lazy loading. ```APIDOC ## Method: GET ### Endpoint `/wiki/Special:EntityData/{entity_id}` (Implicitly used by the client) ### Description Get a Wikidata entity by its `EntityId`. ### Method GET ### Endpoint Internal client method, not a direct HTTP endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters * **entity_id** (`EntityId`) - Required - The `id` of the `Entity` to find. * **load** (`bool`) - Optional - Eager loading on `True`. Lazy loading (`False`) by default. ### Request Example ```python from wikidata.client import Client client = Client() entity_id = "Q42" entity = client.get(entity_id, load=True) print(entity.label()) ``` ### Response #### Success Response (200) * **Entity** (`Entity`) - The found entity object. #### Response Example ```json { "id": "Q42", "type": "item", "labels": { "en": {"language": "en", "value": "Douglas Adams"} }, "descriptions": { "en": {"language": "en", "value": "English writer and satirist"} } } ``` ``` -------------------------------- ### Retrieve Single Property Value from Entity Source: https://context7.com/dahlia/wikidata/llms.txt Explains how to retrieve a single property value from a Wikidata entity. It uses dictionary-style access to get the property entity and then accesses its attributes like image URL and resolution. ```python from wikidata.client import Client client = Client() entity = client.get('Q20145', load=True) # Get property entity (P18 is "image") image_prop = client.get('P18') # Access property value using dictionary-style access image = entity[image_prop] print(image) # print(image.image_url) # 'https://upload.wikimedia.org/wikipedia/commons/...' print(image.image_resolution) # (820, 1122) print(image.image_mimetype) # 'image/jpeg' ``` -------------------------------- ### ProxyCachePolicy Class Definition Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/cache.md Defines the ProxyCachePolicy class, which acts as a proxy to another cache object. It requires a cache_object and allows configuration of timeouts and a namespace for cache keys. The adapted cache object must implement get, set, and delete methods. ```python3 class wikidata.cache.ProxyCachePolicy(cache_object, timeout: int, property_timeout: int | None = None, namespace: str = 'wd_') This proxy policy is a proxy or an adaptor to another cache object. Cache objects can be anything if they satisfy the following interface: def get(key: str) -> Optional[bytes]: pass def set(key: str, value: bytes, timeout: int=0) -> None: pass def delete(key: str) -> None: pass (The above methods omit `self` parameters.) It’s compatible with de facto interface for caching libraries in Python (e.g. python-memcached, `werkzeug.contrib.cache`). * **Parameters:** * **cache_object** – The cache object to adapt. Read the above explanation. * **timeout** (int) – Lifespan of every cache in seconds. 0 means no expiration. * **property_timeout** (int) – Lifespan of caches for properties (in seconds). Since properties don’t change frequently or their changes usually don’t make important effect, longer lifespan of properties’ cache can be useful. 0 means no expiration. Set to the same as `timeout` by default. * **namespace** (str) – The common prefix attached to every cache key. `'wd_'` by default. ``` -------------------------------- ### Get Monolingual Text Property (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Fetches an entity by its ID and retrieves its 'title' property, which is expected to be a MonolingualText object. It then prints the text content and its language code. Handles potential KeyErrors if the property is not found. ```python from wikidata.client import Client client = Client() # Get entity with monolingual text property entity = client.get('Q494290', load=True) # Some entity with text # P1476 is "title" which returns MonolingualText title_prop = client.get('P1476') try: title = entity[title_prop] print(title) # The text content print(title.locale) # Language code like 'en', 'fr', etc. except KeyError: print("Property not found") ``` -------------------------------- ### Wikidata Client Initialization Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/client.md This section details how to initialize the Wikidata client session with various configuration options. ```APIDOC ## Class: wikidata.client.Client ### Description Wikidata client session. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initialization Parameters * **base_url** (`str`) - The base url of the Wikidata. `https://www.wikidata.org/` is used by default. * **opener** (`urllib.request.OpenerDirector` | `None`) - The opener for `urllib.request`. If omitted or `None` the default opener is used. * **datavalue_decoder** (`Decoder` | `Callable`[[`Client`, `str`, `Mapping`[`str`, `object`]], `object`] | `None`) - The function to decode the given datavalue. It’s typically an instance of `Decoder` or its subclass. * **entity_type_guess** (`bool`) - Whether to guess `type` of `Entity` from its `id` for less HTTP requests. `True` by default. * **cache_policy** (`CachePolicy`) - A caching policy for API calls. No cache (`NullCachePolicy`) by default. * **repr_string** (`str` | `None`) - String representation for the client. * **user_agent** (`str`) - User agent string for the client. Defaults to 'WikidataClientPython (https://github.com/dahlia/wikidata; hong@minhee.org)'. ### Request Example ```python from wikidata.client import Client client = Client() ``` ### Response #### Success Response (200) N/A (Initialization does not return a response in the typical HTTP sense.) #### Response Example N/A ``` -------------------------------- ### Initialize Basic Wikidata Client and Retrieve Entity Source: https://context7.com/dahlia/wikidata/llms.txt Demonstrates how to create a basic Wikidata client with default settings and retrieve an entity by its ID. It shows how to access the entity's label and description. ```python from wikidata.client import Client # Create client with default settings (no caching) client = Client() # Get an entity by its ID (Q20145 is IU, the South Korean singer) entity = client.get('Q20145', load=True) print(entity) # print(entity.label) # m'IU' print(entity.description) # m'South Korean singer and actress' ``` -------------------------------- ### Python Wikidata Client Initialization and Entity Retrieval Source: https://github.com/dahlia/wikidata/blob/main/README.rst Demonstrates how to initialize the Wikidata client and retrieve an entity by its ID. It shows loading the entity's full data and accessing its description. Dependencies: 'wikidata' library. ```python from wikidata.client import Client client = Client() entity = client.get('Q20145', load=True) print(entity) print(entity.description) ``` -------------------------------- ### Basic Wikidata Entity and Image Retrieval in Python Source: https://github.com/dahlia/wikidata/blob/main/docs/index.md Demonstrates how to initialize the Wikidata client, fetch an entity by its ID, retrieve its description, and access associated images, including image resolution and URL. Requires the 'Wikidata' package. ```python >>> from wikidata.client import Client >>> client = Client() >>> entity = client.get('Q20145', load=True) >>> entity >>> entity.description m'South Korean singer and actress' >>> image_prop = client.get('P18') >>> image = entity[image_prop] >>> image >>> image.image_resolution (820, 1122) >>> image.image_url 'https://upload.wikimedia.org/wikipedia/commons/6/60/KBS_%22The_Producers%22_press_conference%2C_11_May_2015_10.jpg' ``` -------------------------------- ### Initialize Wikidata Client with Custom URL and Cache Policy Source: https://context7.com/dahlia/wikidata/llms.txt Shows how to initialize a Wikidata client with a custom base URL and an in-memory LRU cache policy. It also demonstrates retrieving an entity with lazy loading and accessing multilingual attributes. ```python from wikidata.client import Client from wikidata.cache import MemoryCachePolicy # Create client with in-memory LRU cache (max 256 items) cache_policy = MemoryCachePolicy(max_size=256) client = Client( base_url='https://www.wikidata.org/', cache_policy=cache_policy, entity_type_guess=True ) # Retrieve entity with lazy loading (default) entity = client.get('Q8646') # Q8646 is Hong Kong # Data loads automatically when accessing attributes print(entity.type) # EntityType.item # Access multilingual attributes print(entity.label['en']) # English label print(entity.label['zh']) # Chinese label ``` -------------------------------- ### Run Test Suite with tox Source: https://github.com/dahlia/wikidata/blob/main/docs/contributing.md Executes the project's test suite across all supported Python interpreters using tox. This command ensures compatibility with different Python versions. ```shell uv run tox ``` -------------------------------- ### Handle Quantity Data Type with Units Source: https://context7.com/dahlia/wikidata/llms.txt Demonstrates how to handle quantity data types from Wikidata, including accessing the amount, unit, and uncertainty bounds. It shows the `Quantity` class and its attributes. ```python from wikidata.client import Client client = Client() # Q2 is "Earth" earth = client.get('Q2', load=True) # P2120 is "mass" mass_prop = client.get('P2120') mass = earth[mass_prop] print(type(mass)) # print(mass.amount) # 5.9722e+24 print(mass.unit) # print(mass.lower_bound) # Uncertainty lower bound print(mass.upper_bound) # Uncertainty upper bound ``` -------------------------------- ### Initialize Wikidata Quantity Object Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/quantity.md Demonstrates the initialization of a `Quantity` object from the `wikidata.quantity` module. This class represents a numerical value with optional uncertainty bounds and a unit of measurement. It requires a float for the amount and optional floats for bounds and a unit entity. ```python from wikidata.entity import Entity from wikidata.quantity import Quantity # Example usage: # Assuming 'meter' is a wikidata.entity.Entity object meter = Entity(id='Q11577', data={...}) quantity_value = Quantity(amount=10.5, lower_bound=0.1, upper_bound=0.2, unit=meter) ``` -------------------------------- ### Handle Multiple Values for a Property and Iterate Properties Source: https://context7.com/dahlia/wikidata/llms.txt Illustrates how to work with properties that have multiple values and how to iterate through all properties and their values for an entity. It uses `getlist` for multiple values and `iterlists` for property iteration. ```python from wikidata.client import Client client = Client() # Get an entity with multiple values for a property entity = client.get('Q1299', load=True) # Q1299 is "The Beatles" # P463 is "member of" property occupation_prop = client.get('P527') # "has part" property # Get all values as a list all_members = entity.getlist(occupation_prop) for member in all_members: print(member) # Iterate over all properties and their values for prop, values in entity.iterlists(): print(f"{prop.label}: {len(values)} value(s)") ``` -------------------------------- ### Checking Entity Existence and State in Wikidata Source: https://context7.com/dahlia/wikidata/llms.txt Illustrates how to check the state of a Wikidata entity, including whether it's loaded, non-existent, or not loaded. It demonstrates fetching an entity that might not exist and attempting to load it to determine its state. ```python from wikidata.client import Client from wikidata.entity import EntityState client = Client() # Get entity without loading (potentially non-existent) entity = client.get('Q99999999999') # Non-existent ID print(entity.state) # EntityState.not_loaded # Try to load the entity entity.load() print(entity.state) # EntityState.non_existent # Compare with an existing entity real_entity = client.get('Q42') real_entity.load() print(real_entity.state) # EntityState.loaded ``` -------------------------------- ### Custom Cache with External Backend (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Sets up a custom caching strategy using an external backend, exemplified by a Redis-like client. It defines a RedisCache class and configures a ProxyCachePolicy with specific timeouts for general cache entries and properties, and a namespace. ```python from wikidata.client import Client from wikidata.cache import ProxyCachePolicy # Example using a Redis-like cache backend class RedisCache: def __init__(self, redis_client): self.redis = redis_client def get(self, key: str): return self.redis.get(key) def set(self, key: str, value: bytes, timeout: int = 0): if timeout > 0: self.redis.setex(key, timeout, value) else: self.redis.set(key, value) def delete(self, key: str): self.redis.delete(key) # Setup (assuming redis_client is configured) # redis_client = redis.Redis(host='localhost', port=6379, db=0) # cache_backend = RedisCache(redis_client) # cache_policy = ProxyCachePolicy( # cache_backend, # timeout=3600, # 1 hour for general cache # property_timeout=86400, # 24 hours for properties # namespace='wikidata_' # ) # client = Client(cache_policy=cache_policy) ``` -------------------------------- ### Handle Time and Date Values Source: https://context7.com/dahlia/wikidata/llms.txt Demonstrates how to retrieve and display time and date values from Wikidata entities, such as dates of birth. The code shows the conversion to Python's `datetime.date` objects. ```python from wikidata.client import Client import datetime client = Client() # Q937 is "Albert Einstein" einstein = client.get('Q937', load=True) # P569 is "date of birth" birth_prop = client.get('P569') birth_date = einstein[birth_prop] print(type(birth_date)) # print(birth_date) ``` -------------------------------- ### Entity Identity and Equality Comparison in Wikidata Source: https://context7.com/dahlia/wikidata/llms.txt Explains how the Wikidata client library handles entity identity and equality. It shows that fetching the same entity multiple times returns the same object instance due to an identity map, and that entities can be compared for equality and used in sets or dictionaries. ```python from wikidata.client import Client client = Client() # Get the same entity twice entity1 = client.get('Q42') entity2 = client.get('Q42') # Identity map ensures the same object instance is returned assert entity1 is entity2 # Equality comparison entity3 = client.get('Q42', load=True) assert entity1 == entity3 # Hash support for use in sets/dicts entity_set = {entity1, entity2, entity3} print(len(entity_set)) # 1 (all are the same entity) ``` -------------------------------- ### Run tox tests in parallel Source: https://github.com/dahlia/wikidata/blob/main/CONTRIBUTING.rst Illustrates how to speed up the test execution process by running 'tox' tests concurrently across multiple Python interpreters. This option is beneficial for larger projects or slower test suites. ```shell uv run tox --parallel ``` -------------------------------- ### Run a specific pytest test Source: https://github.com/dahlia/wikidata/blob/main/CONTRIBUTING.rst Shows how to execute a single, specific test function within the project using 'pytest'. The command targets a particular test file and function, with the '-v' flag enabling verbose output for detailed information. ```shell uv run pytest tests/client_test.py::test_client_get -v ``` -------------------------------- ### Accessing Multilingual Labels and Descriptions in Wikidata Source: https://context7.com/dahlia/wikidata/llms.txt Shows how to fetch and display labels and descriptions for a Wikidata entity ('Earth', Q2) in various languages. It covers accessing specific language translations, checking available languages, and iterating through all translations. ```python from wikidata.client import Client client = Client() entity = client.get('Q2', load=True) # Q2 is "Earth" # Access label in different languages print(entity.label['en']) # English print(entity.label['de']) # German print(entity.label['ja']) # Japanese print(entity.label['ar']) # Arabic # Default string representation prefers English print(str(entity.label)) # 'Earth' # Check available languages print(list(entity.label.keys())[:5]) # ['en', 'de', 'fr', 'ja', ...] # Get description in specific language print(entity.description['en']) # 'third planet from the Sun in the Solar System' # Iterate over all available translations for locale in entity.label: print(f"{locale}: {entity.label[locale]}") ``` -------------------------------- ### Accessing Entity Types and Guessing Types with Wikidata Client Source: https://context7.com/dahlia/wikidata/llms.txt Demonstrates how to retrieve Wikidata items and properties using their IDs and how the client can automatically guess the entity type based on the ID prefix. This is useful for identifying whether an ID refers to an item or a property. ```python from wikidata.client import Client client = Client() # Accessing an item item = client.get('Q42', load=True) print(item.type) # EntityType.item # Accessing a property prop = client.get('P31') print(prop.type) # EntityType.property # Guessing entity type from ID prefix guessed_type = client.guess_entity_type('Q12345') print(guessed_type) # EntityType.item guessed_type = client.guess_entity_type('P567') print(guessed_type) # EntityType.property ``` -------------------------------- ### Iterating Over Wikidata Entity Properties and Values Source: https://context7.com/dahlia/wikidata/llms.txt Demonstrates how to iterate through the properties and values associated with a Wikidata entity. It covers iterating over property entities, accessing property-value pairs, and handling properties with multiple values. ```python from wikidata.client import Client client = Client() entity = client.get('Q42', load=True) # Douglas Adams # Iterate over all properties (returns property entities) for property_entity in entity: print(f"Property: {property_entity.id} - {property_entity.label}") # Get all property-value pairs for prop, value in entity.items(): print(f"{prop.label}: {value}") # Get all property-values pairs (with multiple values) for prop, values in entity.lists(): print(f"{prop.label}: {len(values)} value(s)") for value in values: print(f" - {value}") ``` -------------------------------- ### In-memory LRU Cache Configuration (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Configures the Wikidata client to use an in-memory Least Recently Used (LRU) cache with a maximum size of 512 entries. Demonstrates that subsequent calls for the same entity are retrieved from the cache. ```python from wikidata.client import Client from wikidata.cache import MemoryCachePolicy # Create LRU cache with maximum 512 entries cache = MemoryCachePolicy(max_size=512) client = Client(cache_policy=cache) # First access - makes HTTP request entity1 = client.get('Q42', load=True) # Second access - retrieved from cache entity2 = client.get('Q42', load=True) # Both are the same object (identity map) assert entity1 is entity2 ``` -------------------------------- ### Perform type checking with mypy Source: https://github.com/dahlia/wikidata/blob/main/CONTRIBUTING.rst This command utilizes 'mypy' to perform static type checking on the 'wikidata' package within the project. It helps identify potential type-related errors before runtime. ```shell uv run mypy -p wikidata ``` -------------------------------- ### Wikidata Cache API Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/cache.md This section details the core components of the Wikidata caching system, including key types, policy interfaces, and specific policy implementations like MemoryCachePolicy and NullCachePolicy. ```APIDOC ## Wikidata Cache Module ### Description Provides caching policies and implementations for the Wikidata project. ### Classes * **`CacheKey`**: Alias for `str`. Represents the type of keys used to look up cached values. * **`CacheValue`**: Alias for `object`. Represents the type of values stored in the cache. * **`CachePolicy`**: Interface for caching policies. * **`get(key: CacheKey)`**: Looks up a cached value by its key. Returns the value if found, otherwise `None`. * **`set(key: CacheKey, value: Optional[CacheValue])`**: Creates or updates a cache entry. Setting `value` to `None` removes the cache entry. * **`MemoryCachePolicy(max_size: int = 128)`**: An LRU (least recently used) cache implemented in memory. * **`max_size`**: The maximum number of values to cache (default is 128). * **`get(key: CacheKey)`**: Looks up a cached value by its key. Returns the value if found, otherwise `None`. * **`set(key: CacheKey, value: Optional[CacheValue])`**: Creates or updates a cache entry. Setting `value` to `None` removes the cache entry. * **`NullCachePolicy`**: A no-operation cache policy. All operations are no-ops. * **`get(key: CacheKey)`**: Returns `None`. * **`set(key: CacheKey, value: Optional[CacheValue])`**: Does nothing. ``` -------------------------------- ### ProxyCachePolicy Set Method Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/cache.md Creates or updates a cache entry with the given key and value. If the value is None, the cache entry is removed. The key is of type CacheKey and the value can be of type CacheValue or None. ```python3 def set(key: CacheKey, value: CacheValue | None) -> None Create or update a cache. * **Parameters:** * **key** (CacheKey) – A key string to create or update. * **value** (Optional[CacheValue]) – A value to cache. `None` to remove cache. ``` -------------------------------- ### Custom Datatype Decoding (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Extends the default Decoder class to provide custom handling for specific datatypes like 'url' and 'external_id'. The 'url__string' method formats URLs as clickable HTML links, and 'external_id__string' prefixes external IDs with 'EXT-'. ```python from wikidata.client import Client from wikidata.datavalue import Decoder from typing import Mapping class CustomDecoder(Decoder): """Custom decoder with additional handling""" def url__string(self, client, datavalue: Mapping[str, object]) -> str: """Handle URL datatype as clickable link""" url = datavalue['value'] return f"{url}" def external_id__string(self, client, datavalue: Mapping[str, object]) -> str: """Custom handling for external IDs""" value = datavalue['value'] # Add custom formatting or validation return f"EXT-{value}" # Use custom decoder custom_decoder = CustomDecoder() client = Client(datavalue_decoder=custom_decoder) entity = client.get('Q42', load=True) # P856 is "official website" with url datatype website_prop = client.get('P856') try: website = entity[website_prop] print(website) # Will use custom url__string decoder except KeyError: pass ``` -------------------------------- ### File Object API Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/commonsmedia.md Represents a file on Wikimedia Commons and provides access to its properties. ```APIDOC ## Class: wikidata.commonsmedia.File ### Description Represents a file on [Wikimedia Commons](https://commons.wikimedia.org/). ### Properties - **image_mimetype** (str | None) - The MIME type of the image. May be `None` if it's not an image. - **image_resolution** (Tuple[int, int] | None) - The (width, height) pair of the image. May be `None` if it's not an image. - **image_size** (int | None) - The size of the image in bytes. May be `None` if it's not an image. - **image_url** (str | None) - The image URL. May be `None` if it's not an image. - **page_url** (str) - The canonical URL of the page. ### Exceptions - **FileError** - Exception raised when something goes wrong with a `File` object. ``` -------------------------------- ### Wikidata Quantity Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/quantity.md Represents a Quantity value with amount, uncertainty bounds, and unit. ```APIDOC ## Class: wikidata.quantity.Quantity ### Description A Quantity value represents a decimal number, together with information about the uncertainty interval of this number, and a unit of measurement. ### Parameters #### Constructor Parameters - **amount** (float) - Required - The decimal number representing the quantity. - **lower_bound** (float | None) - Optional - The lower bound of the uncertainty interval. - **upper_bound** (float | None) - Optional - The upper bound of the uncertainty interval. - **unit** (Entity | None) - Optional - The unit of measurement for the quantity. ### Version Added Added in version 0.7.0. ### Example ```python from wikidata.quantity import Quantity from wikidata.entity import Entity # Example with amount only qty1 = Quantity(amount=10.5) # Example with amount and uncertainty qty2 = Quantity(amount=25.0, lower_bound=24.5, upper_bound=25.5) # Example with amount and unit # Assuming you have an Entity object for 'meter' (Q11577) # meter_entity = Entity('Q11577') # qty3 = Quantity(amount=5.0, unit=meter_entity) # Example with all parameters # qty4 = Quantity(amount=100.0, lower_bound=99.0, upper_bound=101.0, unit=meter_entity) ``` ### Response (This is a class definition, not an API endpoint with request/response. The 'Response' section describes the attributes of the Quantity object.) #### Attributes - **amount** (float) - The decimal number value. - **lower_bound** (float | None) - The lower bound of the uncertainty. - **upper_bound** (float | None) - The upper bound of the uncertainty. - **unit** (Entity | None) - The unit of measurement. ``` -------------------------------- ### ProxyCachePolicy Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/cache.md Documentation for the ProxyCachePolicy class, which acts as a proxy or adaptor to another cache object. ```APIDOC ## wikidata.cache.ProxyCachePolicy ### Description This proxy policy is a proxy or an adaptor to another cache object. It is compatible with de facto interfaces for caching libraries in Python. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Methods #### get(key: CacheKey) -> CacheValue | None ##### Description Look up a cached value by its `key`. ##### Parameters - **key** (CacheKey) - Required - The key string to look up a cached value. ##### Returns - The cached value if it exists. `None` if there’s no such `key`. ##### Return Type Optional[CacheValue] #### set(key: CacheKey, value: CacheValue | None) ##### Description Create or update a cache. Setting the value to `None` will remove the cache entry. ##### Parameters - **key** (CacheKey) - Required - A key string to create or update. - **value** (Optional[CacheValue]) - Required - A value to cache. `None` to remove cache. ##### Returns None ### Request Example ```json { "example": "No request body for get or set methods. Use appropriate client library methods." } ``` ### Response #### Success Response (200) - **value** (CacheValue | None) - The cached value or None if not found. #### Response Example ```json { "example": "Example response depends on the cached data. For get: returned value or null. For set: no direct response body, typically None." } ``` ``` -------------------------------- ### Wikidata Base URL Configuration (Python) Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/client.md Defines the default base URL for the Wikidata client. This constant was updated in version 0.3.0 to use 'https://www.wikidata.org/' from the previous 'https://www.wikidata.org/wiki/'. ```python wikidataclient.client.WIKIDATA_BASE_URL = 'https://www.wikidata.org/' ``` -------------------------------- ### Datavalue Decoder Interface Signature Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/datavalue.md Defines the expected signature for a callable that can decode datavalues. It takes a Wikidata client, a datatype string, and a mapping of datavalue components, returning the decoded object. This allows for flexible implementation beyond subclassing the default Decoder. ```python3 typing.Callable[[wikidata.client.Client, str, typing.Mapping[str, object]], object] ``` -------------------------------- ### Handle Geographic Coordinates Data Type Source: https://context7.com/dahlia/wikidata/llms.txt Explains how to process geographic coordinate data from Wikidata entities. It shows how to access latitude, longitude, globe, and precision using the `GlobeCoordinate` class. ```python from wikidata.client import Client client = Client() # Q84 is "London" london = client.get('Q84', load=True) # P625 is "coordinate location" coord_prop = client.get('P625') coordinates = london[coord_prop] print(type(coordinates)) # print(f"Latitude: {coordinates.latitude}") # Latitude: 51.507222222222225 print(f"Longitude: {coordinates.longitude}") # Longitude: -0.1275 print(f"Globe: {coordinates.globe}") # print(f"Precision: {coordinates.precision}") # Precision value indicating accuracy ``` -------------------------------- ### MonolingualText Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/multilingual.md Represents text in a specific language, equivalent to a string but with an associated locale. ```APIDOC ## Class: wikidata.multilingual.MonolingualText ### Description Locale-denoted text. It's almost equivalent to `str` (and indeed subclasses `str`) except that it has an extra attribute, `locale`, that denotes what language the text is written in. ### Attributes - **locale** ([Locale](#wikidata.multilingual.Locale)) - The code of the locale. ### Version History - **Changed in version 0.8.0**: The type hint of the constructor’s `locale` parameter became `Locale`. - **Changed in version 0.7.0**: The type became `Locale` (was `babel.core.Locale`). ``` -------------------------------- ### Decode Datavalue Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/client.md Decodes a datavalue using the configured datavalue decoder. ```APIDOC ## Method: POST ### Endpoint Internal client method, not a direct HTTP endpoint. ### Description Decode the given `datavalue` using the configured `datavalue_decoder`. ### Method POST ### Endpoint Internal client method, not a direct HTTP endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters * **datatype** (`str`) - Required - The datatype of the datavalue. * **datavalue** (`Mapping`[`str`, `object`]) - Required - The datavalue to decode. ### Request Example ```python from wikidata.client import Client from wikidata.datavalue import Decoder # Assuming a client and a datavalue are initialized client = Client() datatype = "string" datavalue = {"type": "string", "value": "Example Value"} decoded_value = client.decode_datavalue(datatype, datavalue) print(decoded_value) ``` ### Response #### Success Response (200) * **object** (`object`) - The decoded datavalue. #### Response Example ```json "Example Value" ``` ``` -------------------------------- ### Wikidata Entity Types and States Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/entity.md Defines the possible types and states for Wikidata entities. ```APIDOC ## Classes: wikidata.entity.EntityId, wikidata.entity.EntityState, wikidata.entity.EntityType ### Class: wikidata.entity.EntityId ### Description The identifier of each `Entity`. Alias of `str`. ### Class: wikidata.entity.EntityState ### Description Defines the state of an `Entity`. ### Version Added Added in version 0.7.0. ### States - **loaded** (`EntityState`) - The entity exists and is already loaded. - **non_existent** (`EntityState`) - The entity does not exist. - **not_loaded** (`EntityState`) - Not loaded yet. Unknown whether the entity exists or not. ### Class: wikidata.entity.EntityType ### Description The enumerated type which consists of two possible values: `item` or `property`. ### Version Added Added in version 0.2.0. ### Types - **item** (`EntityType`) - Items are `Entity` objects that are typically represented by Wikipage. They can be viewed as “the thing that a Wikipage is about.” - See Also: [Items](https://www.mediawiki.org/wiki/Wikibase/DataModel#Items) - **property** (`EntityType`) - Properties represent relationships or attributes of items. ``` -------------------------------- ### Downloading Wikimedia Commons Files (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Downloads an image file associated with a Wikidata entity. It retrieves the entity, extracts the image URL using the 'P18' property, and then uses `urllib.request.urlretrieve` to save the image to a local file. ```python from wikidata.client import Client import urllib.request client = Client() entity = client.get('Q8646', load=True) # Get image from entity image_prop = client.get('P18') try: file = entity[image_prop] if file.image_url: # Download the image output_path = f"downloaded_{file.title.split(':')[-1]}" urllib.request.urlretrieve(file.image_url, output_path) print(f"Downloaded to {output_path}") except KeyError: print("No image property found") ``` -------------------------------- ### Accessing Wikimedia Commons File Metadata (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Retrieves an entity with an 'image' property (P18) and extracts various metadata about the associated file, including its title, page URL, direct image URL, resolution, file size, and MIME type. ```python from wikidata.client import Client client = Client() # Get entity with image property entity = client.get('Q20145', load=True) # P18 is "image" property image_prop = client.get('P18') file = entity[image_prop] print(f"Title: {file.title}") # Title: File:... print(f"Page URL: {file.page_url}") # https://commons.wikimedia.org/wiki/File:... print(f"Direct Image URL: {file.image_url}") # https://upload.wikimedia.org/wikipedia/commons/... print(f"Resolution: {file.image_resolution}") # (width, height) tuple print(f"File Size: {file.image_size} bytes") # Size in bytes print(f"MIME Type: {file.image_mimetype}") # image/jpeg or image/png, etc. ``` -------------------------------- ### Locale Type Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/multilingual.md Represents the locale of a text, typically a language code. It is an alias for `str`. ```APIDOC ## Type: wikidata.multilingual.Locale ### Description The locale of each [`MonolingualText`](#wikidata.multilingual.MonolingualText) or internal mapping of each [`MultilingualText`](#wikidata.multilingual.MultilingualText). Alias of `str`. ### Version History - **Added in version 0.7.0** ``` -------------------------------- ### MultilingualText Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/multilingual.md Represents text that can have multiple translations, mapped by locale. ```APIDOC ## Class: wikidata.multilingual.MultilingualText ### Description A mapping of locales to text strings, allowing for multilingual content representation. ### Attributes - **texts** (Mapping[Locale | str, str]) - A dictionary where keys are locales or strings and values are the corresponding text translations. ``` -------------------------------- ### Disable Caching (Python) Source: https://context7.com/dahlia/wikidata/llms.txt Explicitly disables all caching mechanisms for the Wikidata client by using the NullCachePolicy. This ensures that every call to client.get() results in a fresh HTTP request. ```python from wikidata.client import Client from wikidata.cache import NullCachePolicy # Explicitly disable caching client = Client(cache_policy=NullCachePolicy()) # Each access makes a fresh HTTP request entity = client.get('Q42', load=True) ``` -------------------------------- ### Guess Entity Type Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/client.md Attempts to guess the entity type from a given entity ID. ```APIDOC ## Method: GET ### Endpoint Internal client method, not a direct HTTP endpoint. ### Description Guess `EntityType` from the given `EntityId`. It could return `None` when it fails to guess. ### Method GET ### Endpoint Internal client method, not a direct HTTP endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters * **entity_id** (`EntityId`) - Required - The `EntityId` to guess the type from. ### Request Example ```python from wikidata.client import Client client = Client() entity_id = "Q42" entity_type = client.guess_entity_type(entity_id) print(entity_type) ``` ### Response #### Success Response (200) * **EntityType** (`EntityType` | `None`) - The guessed entity type (e.g., 'item', 'property') or `None` if guessing fails. #### Response Example ```json "item" ``` ``` -------------------------------- ### Wikidata Datavalue Decoder Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/datavalue.md The default Decoder class for interpreting Wikidata datavalues. It employs the visitor pattern, automatically dispatching to specific methods based on the datavalue type and datatype. This class is intended to be subclassed for custom decoding logic. ```python3 class wikidata.datavalue.Decoder: Decode the given datavalue to a value of the appropriate Python type. For extensibility it uses visitor pattern and is intended to be subclassed. To customize decoding of datavalues subclass it and configure `datavalue_decoder` option of [`Client`](client.md#wikidata.client.Client) to the customized decoder. It automatically invokes an appropriate visitor method using a simple rule of name: `{datatype}__{datavalue[type]}`. For example, if the following call to a `decoder` was made: ```python decoder(client, 'mydatatype', {'type': 'mytype', 'value': '...'})``` it’s delegated to the following visitor method call: > decoder.mydatatype__mytype(client, {‘type’: ‘mytype’, ‘value’: ‘…’}) If a decoder failed to find a visitor method matched to `{datatype}__{datavalue[type]}` pattern it secondly try to find a general version of visitor method: `{datavalue[type]}` which lacks double underscores. For example, for the following call: ```python decoder(client, 'mydatatype', {'type': 'mytype', 'value': '...'})``` It firstly try to find the following visitor method: > decoder.mydatatype__mytype but if there’s no such method it secondly try to find the following general visitor method: > decoder.mytype This twice-try dispatch is useful when to make a visitor method to be matched regardless of datatype. If its `datavalue[type]` contains hyphens they’re replaced by underscores. For example: ```python decoder(client, 'string', {'type': 'wikibase-entityid', 'value': 'a text value'}) ``` the above call is delegated to the following visitor method call: ```python decoder.string__wikibase_entityid( # Note that the ^ underscore client, {'type': 'wikibase-entityid', 'value': 'a text value'} ) ``` ``` -------------------------------- ### wikidata.entity.Entity Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/entity.md Represents a Wikidata entity, which can be either an item or a property. Entity attributes can be loaded lazily. Use Client.get() to retrieve entities. ```APIDOC ## Class: wikidata.entity.Entity ### Description Represents a Wikidata entity. Can be an item or a property. Its attributes can be lazily loaded. To get an entity, use the `Client.get()` method. ### Note Although it implements `Mapping` and `EntityId`, it is actually a multidict. See also `getlist()` method. ### Version Changed - Changed in version 0.2.0: Implemented `Mapping` and `EntityId` protocol for easy access of statement values. - Changed in version 0.2.0: Implemented `Hashable` protocol and `==`/`=` operators for equality test. ### Attributes - **state** (`EntityState`) - The loading state of the entity. - Version Added: 0.7.0 ### Methods - **getlist(key: Entity)** -> Sequence[object] - Description: Returns all values associated with the given `key` property in a sequence. - Parameters: - **key** (`Entity`) - The property entity. - Returns: A sequence of all values associated with the given `key` property. It can be empty if nothing is associated with the property. - Return Type: `Sequence[object]` - **lists()** -> Sequence[Tuple[Entity, Sequence[object]]] - Description: Similar to `items()` except the returning pairs have each list of values instead of each single value. - Returns: The pairs of (key, values) where values is a sequence. - Return Type: `Sequence[Tuple[Entity, Sequence[object]]]` ### Properties - **type** (`EntityType`) - The type of entity, either `item` or `property`. - Version Added: 0.2.0 ``` -------------------------------- ### GlobeCoordinate Class Source: https://github.com/dahlia/wikidata/blob/main/docs/wikidata/globecoordinate.md Represents a geographical position with latitude, longitude, and associated globe information. Includes precision for the coordinate. ```APIDOC ## GlobeCoordinate Class ### Description Literal data for a geographical position given as a latitude-longitude pair in gms or decimal degrees for the given stellar body. This class is part of the Wikidata project and is used to store and manage global coordinate information. ### Method N/A (Class Definition) ### Endpoint N/A (Class Definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body N/A (Class Definition) ### Request Example ```python from wikidata.entity import Entity from wikidata.globecoordinate import GlobeCoordinate # Assuming 'my_globe_entity' is an instance of wikidata.entity.Entity my_globe_entity = Entity('Q123') coord = GlobeCoordinate(latitude=48.8566, longitude=2.3522, globe=my_globe_entity, precision=0.001) print(coord) ``` ### Response #### Success Response (200) N/A (Class Definition) #### Response Example ```python # Example representation of a GlobeCoordinate object # GlobeCoordinate(latitude=48.8566, longitude=2.3522, globe=Entity('Q123'), precision=0.001) ``` ### Version Added Added in version 0.7.0. ```