pywikibot
— Base Classes and Functions#
The initialization file for the Pywikibot framework.
Imports from bot
module
The following classes and functions are inported from bot
module
but can also be used as pywikibot
members:
Imports from i18n
module
The following function is inported from i18n
module but can also be
used as pywikibot
members:
Imports from logging
module
The following functions are inported from logging
module but can
also be used as pywikibot
members:
Imports from page
module
The following classes and function are inported from page
module
but can also be used as pywikibot
members:
Imports from time
module
The following class is inported from time
module
but can also be used as pywikibot
members:
- class pywikibot.Coordinate(lat, lon, alt=None, precision=None, globe=None, typ='', name='', dim=None, site=None, globe_item=None, primary=False)[source]#
Bases:
WbRepresentation
Class for handling and storing Coordinates.
Represent a geo coordinate.
- Parameters:
lat (float) – Latitude
lon (float) – Longitude
alt (float | None) – Altitude
precision (float | None) – precision
globe (str | None) – Which globe the point is on
typ (str) – The type of coordinate point
name (str) – The name
dim (int | None) – Dimension (in meters)
site (DataSite | None) – The Wikibase site
globe_item (ItemPageStrNoneType) – The Wikibase item for the globe, or the entity URI of this Wikibase item. Takes precedence over ‘globe’ if present.
primary (bool) – True for a primary set of coordinates
- property entity: str#
Return the entity uri of the globe.
- classmethod fromWikibase(data, site=None)[source]#
Constructor to create an object from Wikibase’s JSON output.
- Parameters:
data (dict[str, Any]) – Wikibase JSON
site (DataSite | None) – The Wikibase site
- Return type:
- get_globe_item(repo=None, lazy_load=False)[source]#
Return the ItemPage corresponding to the globe.
Note that the globe need not be in the same data repository as the Coordinate itself.
A successful lookup is stored as an internal value to avoid the need for repeated lookups.
- Parameters:
repo (DataSite | None) – the Wikibase site for the globe, if different from that provided with the Coordinate.
lazy_load (bool) – Do not raise NoPage if ItemPage does not exist.
- Returns:
pywikibot.ItemPage
- Return type:
pywikibot.ItemPage
- property precision: float | None#
Return the precision of the geo coordinate.
The precision is calculated if the Coordinate does not have a precision, and self._dim is set.
When no precision and no self._dim exists, None is returned.
The biggest error (in degrees) will be given by the longitudinal error; the same error in meters becomes larger (in degrees) further up north. We can thus ignore the latitudinal error.
The longitudinal can be derived as follows:
In small angle approximation (and thus in radians):
\(M{Δλ ≈ Δpos / r_φ}\), where \(r_φ\) is the radius of earth at the given latitude. \(Δλ\) is the error in longitude.
\(M{r_φ = r cos(φ)}\), where \(r\) is the radius of earth, \(φ\) the latitude
Therefore:
precision = math.degrees( self._dim / (radius * math.cos(math.radians(self.lat))))
- precisionToDim()[source]#
Convert precision from Wikibase to GeoData’s dim and return the latter.
dim is calculated if the Coordinate doesn’t have a dimension, and precision is set. When neither dim nor precision are set, ValueError is thrown.
Carrying on from the earlier derivation of precision, since
precision = math.degrees( dim / (radius * math.cos(math.radians(self.lat))))
we get:
dim = math.radians( precision) * radius * math.cos(math.radians(self.lat))
But this is not valid, since it returns a float value for dim which is an integer. We must round it off to the nearest integer.
Therefore:
dim = int(round(math.radians( precision)*radius*math.cos(math.radians(self.lat))))
- Return type:
int | None
- pywikibot.Site(code=None, fam=None, user=None, *, interface=None, url=None)[source]#
A factory method to obtain a Site object.
Site objects are cached and reused by this method.
By default rely on config settings. These defaults may all be overridden using the method parameters.
Creating the default site using config.mylang and config.family:
site = pywikibot.Site()
Override default site code:
site = pywikibot.Site('fr')
Override default family:
site = pywikibot.Site(fam='wikisource')
Setting a specific site:
site = pywikibot.Site('fr', 'wikisource')
which is equal to:
site = pywikibot.Site('wikisource:fr')
Note
An already created site is cached an a new variable points to the same object if interface, family, code and user are equal:
>>> import pywikibot >>> site_1 = pywikibot.Site('wikisource:fr') >>> site_2 = pywikibot.Site('fr', 'wikisource') >>> site_1 is site_2 True >>> site_1 APISite("fr", "wikisource")
APISite
is the default interface. Referpywikibot.site
for other interface types.Warning
Never create a site object via interface class directly. Always use this factory method.
Changed in version 7.3: Short creation if site code is equal to family name like
Site('commons')
,Site('meta')
orSite('wikidata')
.- Parameters:
code (str | None) – language code (override config.mylang) code may also be a sitename like ‘wikipedia:test’
fam (str | Family | None) – family name or object (override config.family)
user (str | None) – bot user name to use on this site (override config.usernames)
interface (str | _BaseSite | None) – site class or name of class in
pywikibot.site
(override config.site_interface)url (str | None) – Instead of code and fam, does try to get a Site based on the URL. Still requires that the family supporting that URL exists.
- Raises:
ValueError – URL and pair of code and family given
ValueError – Invalid interface name
ValueError – Missing Site code
ValueError – Missing Site family
- Return type:
_BaseSite
- class pywikibot.WbGeoShape(page, site=None)[source]#
Bases:
WbDataPage
A Wikibase geo-shape representation.
Create a new WbDataPage object.
- Parameters:
page (pywikibot.Page) – page containing the data
site (DataSite | None) – The Wikibase site
- class pywikibot.WbMonolingualText(text, language)[source]#
Bases:
WbRepresentation
A Wikibase monolingual text representation.
Create a new WbMonolingualText object.
- Parameters:
text (str) – text string
language (str) – language code of the string
- class pywikibot.WbQuantity(amount, unit=None, error=None, site=None)[source]#
Bases:
WbRepresentation
A Wikibase quantity representation.
Create a new WbQuantity object.
- Parameters:
amount (ToDecimalType) – number representing this quantity
unit (ItemPageStrNoneType) – the Wikibase item for the unit or the entity URI of this Wikibase item.
error (ToDecimalType | tuple[ToDecimalType, ToDecimalType]) – the uncertainty of the amount (e.g. ±1)
site (DataSite | None) – The Wikibase site
- classmethod fromWikibase(data, site=None)[source]#
Create a WbQuantity from the JSON data given by the Wikibase API.
- Parameters:
data (dict[str, Any]) – Wikibase JSON
site (DataSite | None) – The Wikibase site
- Return type:
- get_unit_item(repo=None, lazy_load=False)[source]#
Return the ItemPage corresponding to the unit.
Note that the unit need not be in the same data repository as the WbQuantity itself.
A successful lookup is stored as an internal value to avoid the need for repeated lookups.
- Parameters:
repo (DataSite | None) – the Wikibase site for the unit, if different from that provided with the WbQuantity.
lazy_load (bool) – Do not raise NoPage if ItemPage does not exist.
- Returns:
pywikibot.ItemPage
- Return type:
pywikibot.ItemPage
- toWikibase()[source]#
Convert the data to a JSON object for the Wikibase API.
- Returns:
Wikibase JSON
- Return type:
dict[str, Any]
- property unit: str#
Return _unit’s entity uri or ‘1’ if _unit is None.
- class pywikibot.WbTabularData(page, site=None)[source]#
Bases:
WbDataPage
A Wikibase tabular-data representation.
Create a new WbDataPage object.
- Parameters:
page (pywikibot.Page) – page containing the data
site (DataSite | None) – The Wikibase site
- class pywikibot.WbTime(year=None, month=None, day=None, hour=None, minute=None, second=None, precision=None, before=0, after=0, timezone=0, calendarmodel=None, site=None)[source]#
Bases:
WbRepresentation
A Wikibase time representation.
Make a WbTime object from the current time:
current_ts = pywikibot.Timestamp.now() wbtime = pywikibot.WbTime.fromTimestamp(current_ts)
For converting python datetime objects to WbTime objects, see
pywikibot.Timestamp
andfromTimestamp()
.Create a new WbTime object.
The precision can be set by the Wikibase int value (0-14) or by a human readable string, e.g.,
hour
. If no precision is given, it is set according to the given time units.Timezone information is given in three different ways depending on the time:
Times after the implementation of UTC (1972): as an offset from UTC in minutes;
Times before the implementation of UTC: the offset of the time zone from universal time;
Before the implementation of time zones: The longitude of the place of the event, in the range −180° to 180°, multiplied by 4 to convert to minutes.
Note
Comparison information: When using the greater than or equal to operator, or the less than or equal to operator, two different time objects with the same UTC time after factoring in timezones are considered equal. However, the equality operator will return false if the timezone is different.
- Parameters:
year (int | None) – The year as a signed integer of between 1 and 16 digits.
month (int | None) – Month of the timestamp, if it exists.
day (int | None) – Day of the timestamp, if it exists.
hour (int | None) – Hour of the timestamp, if it exists.
minute (int | None) – Minute of the timestamp, if it exists.
second (int | None) – Second of the timestamp, if it exists.
precision (int | str | None) – The unit of the precision of the time.
before (int) – Number of units after the given time it could be, if uncertain. The unit is given by the precision.
after (int) – Number of units before the given time it could be, if uncertain. The unit is given by the precision.
timezone (int) – Timezone information in minutes.
calendarmodel (str | None) – URI identifying the calendar model.
site (DataSite | None) – The Wikibase site. If not provided, retrieves the data repository from the default site from user-config.py. Only used if calendarmodel is not given.
- FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'#
- PRECISION = {'10000': 5, '100000': 4, '1000000': 3, '10000000': 2, '100000000': 1, '1000000000': 0, 'century': 7, 'day': 11, 'decade': 8, 'hour': 12, 'millenia': 6, 'minute': 13, 'month': 10, 'second': 14, 'year': 9}#
- equal_instant(other)[source]#
Checks if the two times represent the same instant in time.
This is different from the equality operator, which will return false for two times that are the same number of UTC seconds, but with different timezone information.
For example, a time with at 10:00 UTC-5 would return false if checked with == with a time at 15:00 UTC, but would return true with this method.
Added in version 9.0.
- Parameters:
other (WbTime)
- Return type:
bool
- classmethod fromTimestamp(timestamp, precision=14, before=0, after=0, timezone=0, calendarmodel=None, site=None, copy_timezone=False)[source]#
Create a new WbTime object from a pywikibot.Timestamp.
Changed in version 8.0: Added copy_timezone parameter.
- Parameters:
timestamp (Timestamp) – Timestamp
precision (int | str) – The unit of the precision of the time. Defaults to 14 (second).
before (int) – Number of units after the given time it could be, if uncertain. The unit is given by the precision.
after (int) – Number of units before the given time it could be, if uncertain. The unit is given by the precision.
timezone (int) – Timezone information in minutes.
calendarmodel (str | None) – URI identifying the calendar model.
site (DataSite | None) – The Wikibase site. If not provided, retrieves the data repository from the default site from user-config.py. Only used if calendarmodel is not given.
copy_timezone (bool) – Whether to copy the timezone from the timestamp if it has timezone information. Defaults to False to maintain backwards compatibility. If a timezone is given, timezone information is discarded.
- Return type:
- classmethod fromTimestr(datetimestr, precision=14, before=0, after=0, timezone=0, calendarmodel=None, site=None)[source]#
Create a new WbTime object from a UTC date/time string.
The timestamp differs from ISO 8601 in that:
The year is always signed and having between 1 and 16 digits;
The month, day and time are zero if they are unknown;
The Z is discarded since time zone is determined from the timezone param.
- Parameters:
datetimestr (str) – Timestamp in a format resembling ISO 8601, e.g. +2013-01-01T00:00:00Z
precision (int | str) – The unit of the precision of the time. Defaults to 14 (second).
before (int) – Number of units after the given time it could be, if uncertain. The unit is given by the precision.
after (int) – Number of units before the given time it could be, if uncertain. The unit is given by the precision.
timezone (int) – Timezone information in minutes.
calendarmodel (str | None) – URI identifying the calendar model.
site (DataSite | None) – The Wikibase site. If not provided, retrieves the data repository from the default site from user-config.py. Only used if calendarmodel is not given.
- Return type:
- classmethod fromWikibase(data, site=None)[source]#
Create a WbTime from the JSON data given by the Wikibase API.
- normalize()[source]#
Normalizes the WbTime object to account for precision.
Normalization is needed because WbTime objects can have hidden values that affect naive comparisons, such as an object set to a precision of YEAR but containing a month and day value.
This function returns a new normalized object and does not do any modification in place.
Normalization will delete timezone information if the precision is less than or equal to DAY.
Note: Normalized WbTime objects can only be compared to other normalized WbTime objects of the same precision. Normalization might make a WbTime object that was less than another WbTime object before normalization, greater than it after normalization, or vice versa.
- Return type:
- toTimestamp(timezone_aware=False)[source]#
Convert the data to a pywikibot.Timestamp.
Changed in version 8.0.1: timezone_aware parameter was added.
- Parameters:
timezone_aware (bool) – Whether the timezone should be passed to the Timestamp object.
- Raises:
ValueError – instance value cannot be represented using Timestamp
- Return type:
- toTimestr(force_iso=False)[source]#
Convert the data to a UTC date/time string.
See also
fromTimestr()
for differences between output with and without force_iso parameter.Changed in version 8.0: normalize parameter was added.
- Parameters:
force_iso (bool) – whether the output should be forced to ISO 8601
- Returns:
Timestamp in a format resembling ISO 8601
- Return type:
str
- class pywikibot.WbUnknown(json)[source]#
Bases:
WbRepresentation
A Wikibase representation for unknown data type.
This will prevent the bot from breaking completely when a new type is introduced.
This data type is just a json container
Added in version 3.0.
Create a new WbUnknown object.
- Parameters:
json (dict[str, Any]) – Wikibase JSON
- pywikibot.async_manager(block=True)[source]#
Daemon to take requests from the queue and execute them in background.
- Parameters:
block – If true, block
page_put_queue
if necessary until a request is available to process. Otherwise process a request if one is immediately available, else leave the function.- Return type:
None
- pywikibot.async_request(request, *args, **kwargs)[source]#
Put a request on the queue, and start the daemon if necessary.
- Parameters:
request (Callable)
args (Any)
kwargs (Any)
- Return type:
None
- pywikibot.page_put_queue: Queue = <queue.Queue object>#
Queue to hold pending requests
- pywikibot.showDiff(oldtext, newtext, context=0)[source]#
Output a string showing the differences between oldtext and newtext.
The differences are highlighted (only on compatible systems) to show which changes were made.
- Parameters:
oldtext (str)
newtext (str)
context (int)
- Return type:
None
- pywikibot.sleep(secs)[source]#
Suspend execution of the current thread for the given number of seconds.
Drop this process from the throttle log if wait time is greater than 30 seconds by calling
stopme()
.- Parameters:
secs (int)
- Return type:
None
- pywikibot.stopme()[source]#
Drop this process from the throttle log, after pending threads finish.
Can be called manually if desired but usually it is not necessary. Does not clean
async_manager()
. This should be run when a bot does not interact with the Wiki, or when it has stopped doing so. After a bot has runstopme()
it will not slow down other bots instances any more.stopme()
is called withsleep()
function during long delays and withbot.BaseBot.exit()
to wait for pending write threads.- Return type:
None