id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,800 | aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.make_prefix | def make_prefix(self, prefix, iterable):
"""
Add prefix to the label
:param prefix:
:param iterable:
:return:
"""
if not prefix:
yield from iterable
for key, value in iterable:
yield f"{prefix}_{key}", value | python | def make_prefix(self, prefix, iterable):
"""
Add prefix to the label
:param prefix:
:param iterable:
:return:
"""
if not prefix:
yield from iterable
for key, value in iterable:
yield f"{prefix}_{key}", value | [
"def",
"make_prefix",
"(",
"self",
",",
"prefix",
",",
"iterable",
")",
":",
"if",
"not",
"prefix",
":",
"yield",
"from",
"iterable",
"for",
"key",
",",
"value",
"in",
"iterable",
":",
"yield",
"f\"{prefix}_{key}\"",
",",
"value"
] | Add prefix to the label
:param prefix:
:param iterable:
:return: | [
"Add",
"prefix",
"to",
"the",
"label"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L233-L245 |
224,801 | aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.process_user | def process_user(self, user: types.User):
"""
Generate user data
:param user:
:return:
"""
if not user:
return
yield 'user_id', user.id
if self.include_content:
yield 'user_full_name', user.full_name
if user.username:
yield 'user_name', f"@{user.username}" | python | def process_user(self, user: types.User):
"""
Generate user data
:param user:
:return:
"""
if not user:
return
yield 'user_id', user.id
if self.include_content:
yield 'user_full_name', user.full_name
if user.username:
yield 'user_name', f"@{user.username}" | [
"def",
"process_user",
"(",
"self",
",",
"user",
":",
"types",
".",
"User",
")",
":",
"if",
"not",
"user",
":",
"return",
"yield",
"'user_id'",
",",
"user",
".",
"id",
"if",
"self",
".",
"include_content",
":",
"yield",
"'user_full_name'",
",",
"user",
... | Generate user data
:param user:
:return: | [
"Generate",
"user",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L247-L261 |
224,802 | aiogram/aiogram | aiogram/contrib/middlewares/logging.py | LoggingFilter.process_chat | def process_chat(self, chat: types.Chat):
"""
Generate chat data
:param chat:
:return:
"""
if not chat:
return
yield 'chat_id', chat.id
yield 'chat_type', chat.type
if self.include_content:
yield 'chat_title', chat.full_name
if chat.username:
yield 'chat_name', f"@{chat.username}" | python | def process_chat(self, chat: types.Chat):
"""
Generate chat data
:param chat:
:return:
"""
if not chat:
return
yield 'chat_id', chat.id
yield 'chat_type', chat.type
if self.include_content:
yield 'chat_title', chat.full_name
if chat.username:
yield 'chat_name', f"@{chat.username}" | [
"def",
"process_chat",
"(",
"self",
",",
"chat",
":",
"types",
".",
"Chat",
")",
":",
"if",
"not",
"chat",
":",
"return",
"yield",
"'chat_id'",
",",
"chat",
".",
"id",
"yield",
"'chat_type'",
",",
"chat",
".",
"type",
"if",
"self",
".",
"include_conten... | Generate chat data
:param chat:
:return: | [
"Generate",
"chat",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/logging.py#L263-L278 |
224,803 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.process_updates | async def process_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process list of updates
:param updates:
:param fast:
:return:
"""
if fast:
tasks = []
for update in updates:
tasks.append(self.updates_handler.notify(update))
return await asyncio.gather(*tasks)
results = []
for update in updates:
results.append(await self.updates_handler.notify(update))
return results | python | async def process_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process list of updates
:param updates:
:param fast:
:return:
"""
if fast:
tasks = []
for update in updates:
tasks.append(self.updates_handler.notify(update))
return await asyncio.gather(*tasks)
results = []
for update in updates:
results.append(await self.updates_handler.notify(update))
return results | [
"async",
"def",
"process_updates",
"(",
"self",
",",
"updates",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
")",
":",
"if",
"fast",
":",
"tasks",
"=",
"[",
"]",
"for",
"update",
"in",
"updates",
":",
"tasks",
".",
"a... | Process list of updates
:param updates:
:param fast:
:return: | [
"Process",
"list",
"of",
"updates"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L130-L147 |
224,804 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.process_update | async def process_update(self, update: types.Update):
"""
Process single update object
:param update:
:return:
"""
types.Update.set_current(update)
try:
if update.message:
types.User.set_current(update.message.from_user)
types.Chat.set_current(update.message.chat)
return await self.message_handlers.notify(update.message)
if update.edited_message:
types.User.set_current(update.edited_message.from_user)
types.Chat.set_current(update.edited_message.chat)
return await self.edited_message_handlers.notify(update.edited_message)
if update.channel_post:
types.Chat.set_current(update.channel_post.chat)
return await self.channel_post_handlers.notify(update.channel_post)
if update.edited_channel_post:
types.Chat.set_current(update.edited_channel_post.chat)
return await self.edited_channel_post_handlers.notify(update.edited_channel_post)
if update.inline_query:
types.User.set_current(update.inline_query.from_user)
return await self.inline_query_handlers.notify(update.inline_query)
if update.chosen_inline_result:
types.User.set_current(update.chosen_inline_result.from_user)
return await self.chosen_inline_result_handlers.notify(update.chosen_inline_result)
if update.callback_query:
if update.callback_query.message:
types.Chat.set_current(update.callback_query.message.chat)
types.User.set_current(update.callback_query.from_user)
return await self.callback_query_handlers.notify(update.callback_query)
if update.shipping_query:
types.User.set_current(update.shipping_query.from_user)
return await self.shipping_query_handlers.notify(update.shipping_query)
if update.pre_checkout_query:
types.User.set_current(update.pre_checkout_query.from_user)
return await self.pre_checkout_query_handlers.notify(update.pre_checkout_query)
if update.poll:
return await self.poll_handlers.notify(update.poll)
except Exception as e:
err = await self.errors_handlers.notify(update, e)
if err:
return err
raise | python | async def process_update(self, update: types.Update):
"""
Process single update object
:param update:
:return:
"""
types.Update.set_current(update)
try:
if update.message:
types.User.set_current(update.message.from_user)
types.Chat.set_current(update.message.chat)
return await self.message_handlers.notify(update.message)
if update.edited_message:
types.User.set_current(update.edited_message.from_user)
types.Chat.set_current(update.edited_message.chat)
return await self.edited_message_handlers.notify(update.edited_message)
if update.channel_post:
types.Chat.set_current(update.channel_post.chat)
return await self.channel_post_handlers.notify(update.channel_post)
if update.edited_channel_post:
types.Chat.set_current(update.edited_channel_post.chat)
return await self.edited_channel_post_handlers.notify(update.edited_channel_post)
if update.inline_query:
types.User.set_current(update.inline_query.from_user)
return await self.inline_query_handlers.notify(update.inline_query)
if update.chosen_inline_result:
types.User.set_current(update.chosen_inline_result.from_user)
return await self.chosen_inline_result_handlers.notify(update.chosen_inline_result)
if update.callback_query:
if update.callback_query.message:
types.Chat.set_current(update.callback_query.message.chat)
types.User.set_current(update.callback_query.from_user)
return await self.callback_query_handlers.notify(update.callback_query)
if update.shipping_query:
types.User.set_current(update.shipping_query.from_user)
return await self.shipping_query_handlers.notify(update.shipping_query)
if update.pre_checkout_query:
types.User.set_current(update.pre_checkout_query.from_user)
return await self.pre_checkout_query_handlers.notify(update.pre_checkout_query)
if update.poll:
return await self.poll_handlers.notify(update.poll)
except Exception as e:
err = await self.errors_handlers.notify(update, e)
if err:
return err
raise | [
"async",
"def",
"process_update",
"(",
"self",
",",
"update",
":",
"types",
".",
"Update",
")",
":",
"types",
".",
"Update",
".",
"set_current",
"(",
"update",
")",
"try",
":",
"if",
"update",
".",
"message",
":",
"types",
".",
"User",
".",
"set_curren... | Process single update object
:param update:
:return: | [
"Process",
"single",
"update",
"object"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L149-L196 |
224,805 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.start_polling | async def start_polling(self,
timeout=20,
relax=0.1,
limit=None,
reset_webhook=None,
fast: typing.Optional[bool] = True,
error_sleep: int = 5):
"""
Start long-polling
:param timeout:
:param relax:
:param limit:
:param reset_webhook:
:param fast:
:return:
"""
if self._polling:
raise RuntimeError('Polling already started')
log.info('Start polling.')
# context.set_value(MODE, LONG_POLLING)
Dispatcher.set_current(self)
Bot.set_current(self.bot)
if reset_webhook is None:
await self.reset_webhook(check=False)
if reset_webhook:
await self.reset_webhook(check=True)
self._polling = True
offset = None
try:
current_request_timeout = self.bot.timeout
if current_request_timeout is not sentinel and timeout is not None:
request_timeout = aiohttp.ClientTimeout(total=current_request_timeout.total + timeout or 1)
else:
request_timeout = None
while self._polling:
try:
with self.bot.request_timeout(request_timeout):
updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout)
except:
log.exception('Cause exception while getting updates.')
await asyncio.sleep(error_sleep)
continue
if updates:
log.debug(f"Received {len(updates)} updates.")
offset = updates[-1].update_id + 1
self.loop.create_task(self._process_polling_updates(updates, fast))
if relax:
await asyncio.sleep(relax)
finally:
self._close_waiter._set_result(None)
log.warning('Polling is stopped.') | python | async def start_polling(self,
timeout=20,
relax=0.1,
limit=None,
reset_webhook=None,
fast: typing.Optional[bool] = True,
error_sleep: int = 5):
"""
Start long-polling
:param timeout:
:param relax:
:param limit:
:param reset_webhook:
:param fast:
:return:
"""
if self._polling:
raise RuntimeError('Polling already started')
log.info('Start polling.')
# context.set_value(MODE, LONG_POLLING)
Dispatcher.set_current(self)
Bot.set_current(self.bot)
if reset_webhook is None:
await self.reset_webhook(check=False)
if reset_webhook:
await self.reset_webhook(check=True)
self._polling = True
offset = None
try:
current_request_timeout = self.bot.timeout
if current_request_timeout is not sentinel and timeout is not None:
request_timeout = aiohttp.ClientTimeout(total=current_request_timeout.total + timeout or 1)
else:
request_timeout = None
while self._polling:
try:
with self.bot.request_timeout(request_timeout):
updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout)
except:
log.exception('Cause exception while getting updates.')
await asyncio.sleep(error_sleep)
continue
if updates:
log.debug(f"Received {len(updates)} updates.")
offset = updates[-1].update_id + 1
self.loop.create_task(self._process_polling_updates(updates, fast))
if relax:
await asyncio.sleep(relax)
finally:
self._close_waiter._set_result(None)
log.warning('Polling is stopped.') | [
"async",
"def",
"start_polling",
"(",
"self",
",",
"timeout",
"=",
"20",
",",
"relax",
"=",
"0.1",
",",
"limit",
"=",
"None",
",",
"reset_webhook",
"=",
"None",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
",",
"error_s... | Start long-polling
:param timeout:
:param relax:
:param limit:
:param reset_webhook:
:param fast:
:return: | [
"Start",
"long",
"-",
"polling"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L212-L272 |
224,806 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher._process_polling_updates | async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process updates received from long-polling.
:param updates: list of updates.
:param fast:
"""
need_to_call = []
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
for response in responses:
if not isinstance(response, BaseResponse):
continue
need_to_call.append(response.execute_response(self.bot))
if need_to_call:
try:
asyncio.gather(*need_to_call)
except TelegramAPIError:
log.exception('Cause exception while processing updates.') | python | async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True):
"""
Process updates received from long-polling.
:param updates: list of updates.
:param fast:
"""
need_to_call = []
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
for response in responses:
if not isinstance(response, BaseResponse):
continue
need_to_call.append(response.execute_response(self.bot))
if need_to_call:
try:
asyncio.gather(*need_to_call)
except TelegramAPIError:
log.exception('Cause exception while processing updates.') | [
"async",
"def",
"_process_polling_updates",
"(",
"self",
",",
"updates",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
")",
":",
"need_to_call",
"=",
"[",
"]",
"for",
"responses",
"in",
"itertools",
".",
"chain",
".",
"from_... | Process updates received from long-polling.
:param updates: list of updates.
:param fast: | [
"Process",
"updates",
"received",
"from",
"long",
"-",
"polling",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L274-L291 |
224,807 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.stop_polling | def stop_polling(self):
"""
Break long-polling process.
:return:
"""
if hasattr(self, '_polling') and self._polling:
log.info('Stop polling...')
self._polling = False | python | def stop_polling(self):
"""
Break long-polling process.
:return:
"""
if hasattr(self, '_polling') and self._polling:
log.info('Stop polling...')
self._polling = False | [
"def",
"stop_polling",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_polling'",
")",
"and",
"self",
".",
"_polling",
":",
"log",
".",
"info",
"(",
"'Stop polling...'",
")",
"self",
".",
"_polling",
"=",
"False"
] | Break long-polling process.
:return: | [
"Break",
"long",
"-",
"polling",
"process",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L293-L301 |
224,808 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_message_handler | def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works only if current state is "first_step"
dp.register_message_handler(step_handler_1, state="first_step")
# If you want to handle all states by one handler, use `state="*"`.
dp.register_message_handler(cancel_handler, commands=['cancel'], state="*")
dp.register_message_handler(cancel_handler, lambda msg: msg.text.lower() == 'cancel', state="*")
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.message_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works only if current state is "first_step"
dp.register_message_handler(step_handler_1, state="first_step")
# If you want to handle all states by one handler, use `state="*"`.
dp.register_message_handler(cancel_handler, commands=['cancel'], state="*")
dp.register_message_handler(cancel_handler, lambda msg: msg.text.lower() == 'cancel', state="*")
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.message_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_message_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"... | Register handler for message
.. code-block:: python3
# This handler works only if state is None (by default).
dp.register_message_handler(cmd_start, commands=['start', 'about'])
dp.register_message_handler(entry_point, commands=['setup'])
# This handler works only if current state is "first_step"
dp.register_message_handler(step_handler_1, state="first_step")
# If you want to handle all states by one handler, use `state="*"`.
dp.register_message_handler(cancel_handler, commands=['cancel'], state="*")
dp.register_message_handler(cancel_handler, lambda msg: msg.text.lower() == 'cancel', state="*")
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:return: decorated function | [
"Register",
"handler",
"for",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L319-L353 |
224,809 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.message_handler | def message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, state=None,
run_task=None, **kwargs):
"""
Decorator for message handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.message_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.message_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter messages by command regular expression:
.. code-block:: python3
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
async def send_welcome(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.message_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.message_handler(lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.message_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.message_handler(lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:param run_task: run callback in task (no wait results)
:return: decorated function
"""
def decorator(callback):
self.register_message_handler(callback, *custom_filters,
commands=commands, regexp=regexp, content_types=content_types,
state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, state=None,
run_task=None, **kwargs):
"""
Decorator for message handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.message_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.message_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter messages by command regular expression:
.. code-block:: python3
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
async def send_welcome(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.message_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.message_handler(lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.message_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.message_handler(lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:param run_task: run callback in task (no wait results)
:return: decorated function
"""
def decorator(callback):
self.register_message_handler(callback, *custom_filters,
commands=commands, regexp=regexp, content_types=content_types,
state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"message_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
... | Decorator for message handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.message_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.message_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter messages by command regular expression:
.. code-block:: python3
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
async def send_welcome(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.message_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.message_handler(lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.message_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.message_handler(lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param kwargs:
:param state:
:param run_task: run callback in task (no wait results)
:return: decorated function | [
"Decorator",
"for",
"message",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L355-L432 |
224,810 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.edited_message_handler | def edited_message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited message handler
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_message_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def edited_message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited message handler
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_message_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"edited_message_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | Decorator for edited message handler
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"edited",
"message",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L458-L486 |
224,811 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_channel_post_handler | def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.channel_post_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.channel_post_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_channel_post_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*"... | Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Register",
"handler",
"for",
"channel",
"post"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L488-L510 |
224,812 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.channel_post_handler | def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"channel_post_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"channel",
"post",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L512-L532 |
224,813 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_edited_channel_post_handler | def register_edited_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None,
content_types=None, state=None, run_task=None, **kwargs):
"""
Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.edited_message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.edited_channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_edited_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None,
content_types=None, state=None, run_task=None, **kwargs):
"""
Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
filters_set = self.filters_factory.resolve(self.edited_message_handlers,
*custom_filters,
commands=commands,
regexp=regexp,
content_types=content_types,
state=state,
**kwargs)
self.edited_channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_edited_channel_post_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
","... | Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Register",
"handler",
"for",
"edited",
"channel",
"post"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L534-L556 |
224,814 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.edited_channel_post_handler | def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | python | def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_edited_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | [
"def",
"edited_channel_post_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"commands",
"=",
"None",
",",
"regexp",
"=",
"None",
",",
"content_types",
"=",
"None",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
... | Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"edited",
"channel",
"post",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L558-L579 |
224,815 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_inline_handler | def register_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for inline query
Example:
.. code-block:: python3
dp.register_inline_handler(some_inline_handler, lambda inline_query: True)
:param callback:
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.inline_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.inline_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for inline query
Example:
.. code-block:: python3
dp.register_inline_handler(some_inline_handler, lambda inline_query: True)
:param callback:
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.inline_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.inline_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_inline_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"custom_filters",
"is",
"None",
":",
"custom_filters",
"=",
"[",
... | Register handler for inline query
Example:
.. code-block:: python3
dp.register_inline_handler(some_inline_handler, lambda inline_query: True)
:param callback:
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Register",
"handler",
"for",
"inline",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L581-L604 |
224,816 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.inline_handler | def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"inline_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_inline_handler",
"(",
"cal... | Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function | [
"Decorator",
"for",
"inline",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L606-L628 |
224,817 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_chosen_inline_handler | def register_chosen_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.chosen_inline_result_handlers,
*custom_filters,
state=state,
**kwargs)
self.chosen_inline_result_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_chosen_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.chosen_inline_result_handlers,
*custom_filters,
state=state,
**kwargs)
self.chosen_inline_result_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_chosen_inline_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"custom_filters",
"is",
"None",
":",
"custom_filters",
"=",
... | Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: | [
"Register",
"handler",
"for",
"chosen",
"inline",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L630-L653 |
224,818 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.chosen_inline_handler | def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for chosen inline query handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(lambda chosen_inline_query: True)
async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
def decorator(callback):
self.register_chosen_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for chosen inline query handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(lambda chosen_inline_query: True)
async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return:
"""
def decorator(callback):
self.register_chosen_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"chosen_inline_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_chosen_inline_handler",... | Decorator for chosen inline query handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(lambda chosen_inline_query: True)
async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: | [
"Decorator",
"for",
"chosen",
"inline",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L655-L677 |
224,819 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_callback_query_handler | def register_callback_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.callback_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.callback_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_callback_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.callback_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.callback_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_callback_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve"... | Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Register",
"handler",
"for",
"callback",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L679-L699 |
224,820 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.callback_query_handler | def callback_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(lambda callback_query: True)
async def some_callback_handler(callback_query: types.CallbackQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_callback_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def callback_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(lambda callback_query: True)
async def some_callback_handler(callback_query: types.CallbackQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_callback_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"callback_query_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_callback_query_handler... | Decorator for callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(lambda callback_query: True)
async def some_callback_handler(callback_query: types.CallbackQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Decorator",
"for",
"callback",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L701-L722 |
224,821 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_shipping_query_handler | def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None,
**kwargs):
"""
Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.shipping_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.shipping_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None,
**kwargs):
"""
Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.shipping_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.shipping_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_shipping_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve"... | Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Register",
"handler",
"for",
"shipping",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L724-L745 |
224,822 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.shipping_query_handler | def shipping_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(lambda shipping_query: True)
async def some_shipping_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_shipping_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | python | def shipping_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(lambda shipping_query: True)
async def some_shipping_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_shipping_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)
return callback
return decorator | [
"def",
"shipping_query_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_shipping_query_handler... | Decorator for shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(lambda shipping_query: True)
async def some_shipping_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Decorator",
"for",
"shipping",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L747-L768 |
224,823 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_pre_checkout_query_handler | def register_pre_checkout_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for pre-checkout query
Example:
.. code-block:: python3
dp.register_pre_checkout_query_handler(some_pre_checkout_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.pre_checkout_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.pre_checkout_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_pre_checkout_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for pre-checkout query
Example:
.. code-block:: python3
dp.register_pre_checkout_query_handler(some_pre_checkout_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
filters_set = self.filters_factory.resolve(self.pre_checkout_query_handlers,
*custom_filters,
state=state,
**kwargs)
self.pre_checkout_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_pre_checkout_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"reso... | Register handler for pre-checkout query
Example:
.. code-block:: python3
dp.register_pre_checkout_query_handler(some_pre_checkout_query_handler, lambda shipping_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Register",
"handler",
"for",
"pre",
"-",
"checkout",
"query"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L770-L790 |
224,824 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.pre_checkout_query_handler | def pre_checkout_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for pre-checkout query handler
Example:
.. code-block:: python3
@dp.pre_checkout_query_handler(lambda shipping_query: True)
async def some_pre_checkout_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_pre_checkout_query_handler(callback, *custom_filters, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | python | def pre_checkout_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for pre-checkout query handler
Example:
.. code-block:: python3
@dp.pre_checkout_query_handler(lambda shipping_query: True)
async def some_pre_checkout_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs:
"""
def decorator(callback):
self.register_pre_checkout_query_handler(callback, *custom_filters, state=state, run_task=run_task,
**kwargs)
return callback
return decorator | [
"def",
"pre_checkout_query_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_pre_checkout_query... | Decorator for pre-checkout query handler
Example:
.. code-block:: python3
@dp.pre_checkout_query_handler(lambda shipping_query: True)
async def some_pre_checkout_query_handler(shipping_query: types.ShippingQuery)
:param state:
:param custom_filters:
:param run_task: run callback in task (no wait results)
:param kwargs: | [
"Decorator",
"for",
"pre",
"-",
"checkout",
"query",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L792-L814 |
224,825 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.register_errors_handler | def register_errors_handler(self, callback, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Register handler for errors
:param callback:
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
"""
filters_set = self.filters_factory.resolve(self.errors_handlers,
*custom_filters,
exception=exception,
**kwargs)
self.errors_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | python | def register_errors_handler(self, callback, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Register handler for errors
:param callback:
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
"""
filters_set = self.filters_factory.resolve(self.errors_handlers,
*custom_filters,
exception=exception,
**kwargs)
self.errors_handlers.register(self._wrap_async_task(callback, run_task), filters_set) | [
"def",
"register_errors_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"exception",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve",
... | Register handler for errors
:param callback:
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results) | [
"Register",
"handler",
"for",
"errors"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L830-L842 |
224,826 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.errors_handler | def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Decorator for errors handler
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
:return:
"""
def decorator(callback):
self.register_errors_handler(self._wrap_async_task(callback, run_task),
*custom_filters, exception=exception, **kwargs)
return callback
return decorator | python | def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs):
"""
Decorator for errors handler
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
:return:
"""
def decorator(callback):
self.register_errors_handler(self._wrap_async_task(callback, run_task),
*custom_filters, exception=exception, **kwargs)
return callback
return decorator | [
"def",
"errors_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"exception",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_errors_handler",
"(",
... | Decorator for errors handler
:param exception: you can make handler for specific errors type
:param run_task: run callback in task (no wait results)
:return: | [
"Decorator",
"for",
"errors",
"handler"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L844-L858 |
224,827 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.current_state | def current_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> FSMContext:
"""
Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.chat.id, user=message.user.id) as state:
pass
state = dp.current_state()
state.set_state('my_state')
:param chat:
:param user:
:return:
"""
if chat is None:
chat_obj = types.Chat.get_current()
chat = chat_obj.id if chat_obj else None
if user is None:
user_obj = types.User.get_current()
user = user_obj.id if user_obj else None
return FSMContext(storage=self.storage, chat=chat, user=user) | python | def current_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> FSMContext:
"""
Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.chat.id, user=message.user.id) as state:
pass
state = dp.current_state()
state.set_state('my_state')
:param chat:
:param user:
:return:
"""
if chat is None:
chat_obj = types.Chat.get_current()
chat = chat_obj.id if chat_obj else None
if user is None:
user_obj = types.User.get_current()
user = user_obj.id if user_obj else None
return FSMContext(storage=self.storage, chat=chat, user=user) | [
"def",
"current_state",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
")"... | Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.chat.id, user=message.user.id) as state:
pass
state = dp.current_state()
state.set_state('my_state')
:param chat:
:param user:
:return: | [
"Get",
"current",
"state",
"for",
"user",
"in",
"chat",
"as",
"context"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L860-L885 |
224,828 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.throttle | async def throttle(self, key, *, rate=None, user=None, chat=None, no_error=None) -> bool:
"""
Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return boolean value instead of raising error
:return: bool
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if no_error is None:
no_error = self.no_throttle_error
if rate is None:
rate = self.throttling_rate_limit
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
# Detect current time
now = time.time()
bucket = await self.storage.get_bucket(chat=chat, user=user)
# Fix bucket
if bucket is None:
bucket = {key: {}}
if key not in bucket:
bucket[key] = {}
data = bucket[key]
# Calculate
called = data.get(LAST_CALL, now)
delta = now - called
result = delta >= rate or delta <= 0
# Save results
data[RESULT] = result
data[RATE_LIMIT] = rate
data[LAST_CALL] = now
data[DELTA] = delta
if not result:
data[EXCEEDED_COUNT] += 1
else:
data[EXCEEDED_COUNT] = 1
bucket[key].update(data)
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
if not result and not no_error:
# Raise if it is allowed
raise Throttled(key=key, chat=chat, user=user, **data)
return result | python | async def throttle(self, key, *, rate=None, user=None, chat=None, no_error=None) -> bool:
"""
Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return boolean value instead of raising error
:return: bool
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if no_error is None:
no_error = self.no_throttle_error
if rate is None:
rate = self.throttling_rate_limit
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
# Detect current time
now = time.time()
bucket = await self.storage.get_bucket(chat=chat, user=user)
# Fix bucket
if bucket is None:
bucket = {key: {}}
if key not in bucket:
bucket[key] = {}
data = bucket[key]
# Calculate
called = data.get(LAST_CALL, now)
delta = now - called
result = delta >= rate or delta <= 0
# Save results
data[RESULT] = result
data[RATE_LIMIT] = rate
data[LAST_CALL] = now
data[DELTA] = delta
if not result:
data[EXCEEDED_COUNT] += 1
else:
data[EXCEEDED_COUNT] = 1
bucket[key].update(data)
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
if not result and not no_error:
# Raise if it is allowed
raise Throttled(key=key, chat=chat, user=user, **data)
return result | [
"async",
"def",
"throttle",
"(",
"self",
",",
"key",
",",
"*",
",",
"rate",
"=",
"None",
",",
"user",
"=",
"None",
",",
"chat",
"=",
"None",
",",
"no_error",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"storage",
".",
"has_buck... | Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return boolean value instead of raising error
:return: bool | [
"Execute",
"throttling",
"manager",
".",
"Returns",
"True",
"if",
"limit",
"has",
"not",
"exceeded",
"otherwise",
"raises",
"ThrottleError",
"or",
"returns",
"False"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L887-L942 |
224,829 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.check_key | async def check_key(self, key, chat=None, user=None):
"""
Get information about key in bucket
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
data = bucket.get(key, {})
return Throttled(key=key, chat=chat, user=user, **data) | python | async def check_key(self, key, chat=None, user=None):
"""
Get information about key in bucket
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
data = bucket.get(key, {})
return Throttled(key=key, chat=chat, user=user, **data) | [
"async",
"def",
"check_key",
"(",
"self",
",",
"key",
",",
"chat",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"storage",
".",
"has_bucket",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'This storage does not provide Leaky B... | Get information about key in bucket
:param key:
:param chat:
:param user:
:return: | [
"Get",
"information",
"about",
"key",
"in",
"bucket"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L944-L962 |
224,830 | aiogram/aiogram | aiogram/dispatcher/dispatcher.py | Dispatcher.release_key | async def release_key(self, key, chat=None, user=None):
"""
Release blocked key
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
if bucket and key in bucket:
del bucket['key']
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
return True
return False | python | async def release_key(self, key, chat=None, user=None):
"""
Release blocked key
:param key:
:param chat:
:param user:
:return:
"""
if not self.storage.has_bucket():
raise RuntimeError('This storage does not provide Leaky Bucket')
if user is None and chat is None:
user = types.User.get_current()
chat = types.Chat.get_current()
bucket = await self.storage.get_bucket(chat=chat, user=user)
if bucket and key in bucket:
del bucket['key']
await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
return True
return False | [
"async",
"def",
"release_key",
"(",
"self",
",",
"key",
",",
"chat",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"storage",
".",
"has_bucket",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'This storage does not provide Leaky... | Release blocked key
:param key:
:param chat:
:param user:
:return: | [
"Release",
"blocked",
"key"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L964-L985 |
224,831 | aiogram/aiogram | aiogram/bot/api.py | check_token | def check_token(token: str) -> bool:
"""
Validate BOT token
:param token:
:return:
"""
if any(x.isspace() for x in token):
raise exceptions.ValidationError('Token is invalid!')
left, sep, right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise exceptions.ValidationError('Token is invalid!')
return True | python | def check_token(token: str) -> bool:
"""
Validate BOT token
:param token:
:return:
"""
if any(x.isspace() for x in token):
raise exceptions.ValidationError('Token is invalid!')
left, sep, right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise exceptions.ValidationError('Token is invalid!')
return True | [
"def",
"check_token",
"(",
"token",
":",
"str",
")",
"->",
"bool",
":",
"if",
"any",
"(",
"x",
".",
"isspace",
"(",
")",
"for",
"x",
"in",
"token",
")",
":",
"raise",
"exceptions",
".",
"ValidationError",
"(",
"'Token is invalid!'",
")",
"left",
",",
... | Validate BOT token
:param token:
:return: | [
"Validate",
"BOT",
"token"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/api.py#L20-L34 |
224,832 | aiogram/aiogram | aiogram/bot/api.py | compose_data | def compose_data(params=None, files=None):
"""
Prepare request data
:param params:
:param files:
:return:
"""
data = aiohttp.formdata.FormData(quote_fields=False)
if params:
for key, value in params.items():
data.add_field(key, str(value))
if files:
for key, f in files.items():
if isinstance(f, tuple):
if len(f) == 2:
filename, fileobj = f
else:
raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
elif isinstance(f, types.InputFile):
filename, fileobj = f.filename, f.file
else:
filename, fileobj = guess_filename(f) or key, f
data.add_field(key, fileobj, filename=filename)
return data | python | def compose_data(params=None, files=None):
"""
Prepare request data
:param params:
:param files:
:return:
"""
data = aiohttp.formdata.FormData(quote_fields=False)
if params:
for key, value in params.items():
data.add_field(key, str(value))
if files:
for key, f in files.items():
if isinstance(f, tuple):
if len(f) == 2:
filename, fileobj = f
else:
raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
elif isinstance(f, types.InputFile):
filename, fileobj = f.filename, f.file
else:
filename, fileobj = guess_filename(f) or key, f
data.add_field(key, fileobj, filename=filename)
return data | [
"def",
"compose_data",
"(",
"params",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"data",
"=",
"aiohttp",
".",
"formdata",
".",
"FormData",
"(",
"quote_fields",
"=",
"False",
")",
"if",
"params",
":",
"for",
"key",
",",
"value",
"in",
"params",
... | Prepare request data
:param params:
:param files:
:return: | [
"Prepare",
"request",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/api.py#L115-L143 |
224,833 | aiogram/aiogram | aiogram/types/user.py | User.full_name | def full_name(self):
"""
You can get full name of user.
:return: str
"""
full_name = self.first_name
if self.last_name:
full_name += ' ' + self.last_name
return full_name | python | def full_name(self):
"""
You can get full name of user.
:return: str
"""
full_name = self.first_name
if self.last_name:
full_name += ' ' + self.last_name
return full_name | [
"def",
"full_name",
"(",
"self",
")",
":",
"full_name",
"=",
"self",
".",
"first_name",
"if",
"self",
".",
"last_name",
":",
"full_name",
"+=",
"' '",
"+",
"self",
".",
"last_name",
"return",
"full_name"
] | You can get full name of user.
:return: str | [
"You",
"can",
"get",
"full",
"name",
"of",
"user",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/user.py#L24-L33 |
224,834 | aiogram/aiogram | aiogram/types/user.py | User.locale | def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_code, sep='-'))
return getattr(self, '_locale') | python | def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_code, sep='-'))
return getattr(self, '_locale') | [
"def",
"locale",
"(",
"self",
")",
"->",
"babel",
".",
"core",
".",
"Locale",
"or",
"None",
":",
"if",
"not",
"self",
".",
"language_code",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_locale'",
")",
":",
"setattr",
"(",
"self"... | Get user's locale
:return: :class:`babel.core.Locale` | [
"Get",
"user",
"s",
"locale"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/user.py#L48-L58 |
224,835 | aiogram/aiogram | aiogram/types/mixins.py | Downloadable.get_file | async def get_file(self):
"""
Get file information
:return: :obj:`aiogram.types.File`
"""
if hasattr(self, 'file_path'):
return self
else:
return await self.bot.get_file(self.file_id) | python | async def get_file(self):
"""
Get file information
:return: :obj:`aiogram.types.File`
"""
if hasattr(self, 'file_path'):
return self
else:
return await self.bot.get_file(self.file_id) | [
"async",
"def",
"get_file",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'file_path'",
")",
":",
"return",
"self",
"else",
":",
"return",
"await",
"self",
".",
"bot",
".",
"get_file",
"(",
"self",
".",
"file_id",
")"
] | Get file information
:return: :obj:`aiogram.types.File` | [
"Get",
"file",
"information"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/mixins.py#L37-L46 |
224,836 | aiogram/aiogram | aiogram/dispatcher/middlewares.py | MiddlewareManager.trigger | async def trigger(self, action: str, args: typing.Iterable):
"""
Call action to middlewares with args lilt.
:param action:
:param args:
:return:
"""
for app in self.applications:
await app.trigger(action, args) | python | async def trigger(self, action: str, args: typing.Iterable):
"""
Call action to middlewares with args lilt.
:param action:
:param args:
:return:
"""
for app in self.applications:
await app.trigger(action, args) | [
"async",
"def",
"trigger",
"(",
"self",
",",
"action",
":",
"str",
",",
"args",
":",
"typing",
".",
"Iterable",
")",
":",
"for",
"app",
"in",
"self",
".",
"applications",
":",
"await",
"app",
".",
"trigger",
"(",
"action",
",",
"args",
")"
] | Call action to middlewares with args lilt.
:param action:
:param args:
:return: | [
"Call",
"action",
"to",
"middlewares",
"with",
"args",
"lilt",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/middlewares.py#L41-L50 |
224,837 | aiogram/aiogram | aiogram/dispatcher/middlewares.py | BaseMiddleware.trigger | async def trigger(self, action, args):
"""
Trigger action.
:param action:
:param args:
:return:
"""
handler_name = f"on_{action}"
handler = getattr(self, handler_name, None)
if not handler:
return None
await handler(*args) | python | async def trigger(self, action, args):
"""
Trigger action.
:param action:
:param args:
:return:
"""
handler_name = f"on_{action}"
handler = getattr(self, handler_name, None)
if not handler:
return None
await handler(*args) | [
"async",
"def",
"trigger",
"(",
"self",
",",
"action",
",",
"args",
")",
":",
"handler_name",
"=",
"f\"on_{action}\"",
"handler",
"=",
"getattr",
"(",
"self",
",",
"handler_name",
",",
"None",
")",
"if",
"not",
"handler",
":",
"return",
"None",
"await",
... | Trigger action.
:param action:
:param args:
:return: | [
"Trigger",
"action",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/middlewares.py#L91-L103 |
224,838 | aiogram/aiogram | aiogram/utils/markdown.py | quote_html | def quote_html(content):
"""
Quote HTML symbols
All <, >, & and " symbols that are not a part of a tag or
an HTML entity must be replaced with the corresponding HTML entities
(< with < > with > & with & and " with ").
:param content: str
:return: str
"""
new_content = ''
for symbol in content:
new_content += HTML_QUOTES_MAP[symbol] if symbol in _HQS else symbol
return new_content | python | def quote_html(content):
"""
Quote HTML symbols
All <, >, & and " symbols that are not a part of a tag or
an HTML entity must be replaced with the corresponding HTML entities
(< with < > with > & with & and " with ").
:param content: str
:return: str
"""
new_content = ''
for symbol in content:
new_content += HTML_QUOTES_MAP[symbol] if symbol in _HQS else symbol
return new_content | [
"def",
"quote_html",
"(",
"content",
")",
":",
"new_content",
"=",
"''",
"for",
"symbol",
"in",
"content",
":",
"new_content",
"+=",
"HTML_QUOTES_MAP",
"[",
"symbol",
"]",
"if",
"symbol",
"in",
"_HQS",
"else",
"symbol",
"return",
"new_content"
] | Quote HTML symbols
All <, >, & and " symbols that are not a part of a tag or
an HTML entity must be replaced with the corresponding HTML entities
(< with < > with > & with & and " with ").
:param content: str
:return: str | [
"Quote",
"HTML",
"symbols"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/markdown.py#L39-L53 |
224,839 | aiogram/aiogram | aiogram/contrib/fsm_storage/redis.py | migrate_redis1_to_redis2 | async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2):
"""
Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return:
"""
if not isinstance(storage1, RedisStorage): # better than assertion
raise TypeError(f"{type(storage1)} is not RedisStorage instance.")
if not isinstance(storage2, RedisStorage):
raise TypeError(f"{type(storage2)} is not RedisStorage instance.")
log = logging.getLogger('aiogram.RedisStorage')
for chat, user in await storage1.get_states_list():
state = await storage1.get_state(chat=chat, user=user)
await storage2.set_state(chat=chat, user=user, state=state)
data = await storage1.get_data(chat=chat, user=user)
await storage2.set_data(chat=chat, user=user, data=data)
bucket = await storage1.get_bucket(chat=chat, user=user)
await storage2.set_bucket(chat=chat, user=user, bucket=bucket)
log.info(f"Migrated user {user} in chat {chat}") | python | async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2):
"""
Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return:
"""
if not isinstance(storage1, RedisStorage): # better than assertion
raise TypeError(f"{type(storage1)} is not RedisStorage instance.")
if not isinstance(storage2, RedisStorage):
raise TypeError(f"{type(storage2)} is not RedisStorage instance.")
log = logging.getLogger('aiogram.RedisStorage')
for chat, user in await storage1.get_states_list():
state = await storage1.get_state(chat=chat, user=user)
await storage2.set_state(chat=chat, user=user, state=state)
data = await storage1.get_data(chat=chat, user=user)
await storage2.set_data(chat=chat, user=user, data=data)
bucket = await storage1.get_bucket(chat=chat, user=user)
await storage2.set_bucket(chat=chat, user=user, bucket=bucket)
log.info(f"Migrated user {user} in chat {chat}") | [
"async",
"def",
"migrate_redis1_to_redis2",
"(",
"storage1",
":",
"RedisStorage",
",",
"storage2",
":",
"RedisStorage2",
")",
":",
"if",
"not",
"isinstance",
"(",
"storage1",
",",
"RedisStorage",
")",
":",
"# better than assertion",
"raise",
"TypeError",
"(",
"f\"... | Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return: | [
"Helper",
"for",
"migrating",
"from",
"RedisStorage",
"to",
"RedisStorage2"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/redis.py#L378-L403 |
224,840 | aiogram/aiogram | aiogram/contrib/fsm_storage/redis.py | RedisStorage.get_record | async def get_record(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> typing.Dict:
"""
Get record from storage
:param chat:
:param user:
:return:
"""
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
conn = await self.redis()
data = await conn.execute('GET', addr)
if data is None:
return {'state': None, 'data': {}}
return json.loads(data) | python | async def get_record(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> typing.Dict:
"""
Get record from storage
:param chat:
:param user:
:return:
"""
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
conn = await self.redis()
data = await conn.execute('GET', addr)
if data is None:
return {'state': None, 'data': {}}
return json.loads(data) | [
"async",
"def",
"get_record",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None... | Get record from storage
:param chat:
:param user:
:return: | [
"Get",
"record",
"from",
"storage"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/redis.py#L77-L94 |
224,841 | aiogram/aiogram | aiogram/contrib/fsm_storage/redis.py | RedisStorage.set_record | async def set_record(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None,
state=None, data=None, bucket=None):
"""
Write record to storage
:param bucket:
:param chat:
:param user:
:param state:
:param data:
:return:
"""
if data is None:
data = {}
if bucket is None:
bucket = {}
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
record = {'state': state, 'data': data, 'bucket': bucket}
conn = await self.redis()
await conn.execute('SET', addr, json.dumps(record)) | python | async def set_record(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None,
state=None, data=None, bucket=None):
"""
Write record to storage
:param bucket:
:param chat:
:param user:
:param state:
:param data:
:return:
"""
if data is None:
data = {}
if bucket is None:
bucket = {}
chat, user = self.check_address(chat=chat, user=user)
addr = f"fsm:{chat}:{user}"
record = {'state': state, 'data': data, 'bucket': bucket}
conn = await self.redis()
await conn.execute('SET', addr, json.dumps(record)) | [
"async",
"def",
"set_record",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None... | Write record to storage
:param bucket:
:param chat:
:param user:
:param state:
:param data:
:return: | [
"Write",
"record",
"to",
"storage"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/fsm_storage/redis.py#L96-L119 |
224,842 | niklasf/python-chess | chess/syzygy.py | Tablebase.add_directory | def add_directory(self, directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True) -> int:
"""
Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found.
"""
num = 0
directory = os.path.abspath(directory)
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
tablename, ext = os.path.splitext(filename)
if is_table_name(tablename) and os.path.isfile(path):
if load_wdl:
if ext == self.variant.tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
if load_dtz:
if ext == self.variant.tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
return num | python | def add_directory(self, directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True) -> int:
"""
Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found.
"""
num = 0
directory = os.path.abspath(directory)
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
tablename, ext = os.path.splitext(filename)
if is_table_name(tablename) and os.path.isfile(path):
if load_wdl:
if ext == self.variant.tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
if load_dtz:
if ext == self.variant.tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
return num | [
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
"."... | Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found. | [
"Adds",
"tables",
"from",
"a",
"directory",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/syzygy.py#L1506-L1539 |
224,843 | niklasf/python-chess | chess/syzygy.py | Tablebase.probe_dtz | def probe_dtz(self, board: chess.Board) -> int:
"""
Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior.
"""
v = self.probe_dtz_no_ep(board)
if not board.ep_square or self.variant.captures_compulsory:
return v
v1 = -3
# Generate all en-passant moves.
for move in board.generate_legal_ep():
board.push(move)
try:
v0_plus, _ = self.probe_ab(board, -2, 2)
v0 = -v0_plus
finally:
board.pop()
if v0 > v1:
v1 = v0
if v1 > -3:
v1 = WDL_TO_DTZ[v1 + 2]
if v < -100:
if v1 >= 0:
v = v1
elif v < 0:
if v1 >= 0 or v1 < -100:
v = v1
elif v > 100:
if v1 > 0:
v = v1
elif v > 0:
if v1 == 1:
v = v1
elif v1 >= 0:
v = v1
else:
if all(board.is_en_passant(move) for move in board.generate_legal_moves()):
v = v1
return v | python | def probe_dtz(self, board: chess.Board) -> int:
"""
Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior.
"""
v = self.probe_dtz_no_ep(board)
if not board.ep_square or self.variant.captures_compulsory:
return v
v1 = -3
# Generate all en-passant moves.
for move in board.generate_legal_ep():
board.push(move)
try:
v0_plus, _ = self.probe_ab(board, -2, 2)
v0 = -v0_plus
finally:
board.pop()
if v0 > v1:
v1 = v0
if v1 > -3:
v1 = WDL_TO_DTZ[v1 + 2]
if v < -100:
if v1 >= 0:
v = v1
elif v < 0:
if v1 >= 0 or v1 < -100:
v = v1
elif v > 100:
if v1 > 0:
v = v1
elif v > 0:
if v1 == 1:
v = v1
elif v1 >= 0:
v = v1
else:
if all(board.is_en_passant(move) for move in board.generate_legal_moves()):
v = v1
return v | [
"def",
"probe_dtz",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
")",
"->",
"int",
":",
"v",
"=",
"self",
".",
"probe_dtz_no_ep",
"(",
"board",
")",
"if",
"not",
"board",
".",
"ep_square",
"or",
"self",
".",
"variant",
".",
"captures_compulso... | Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior. | [
"Probes",
"DTZ",
"tables",
"for",
"distance",
"to",
"zero",
"information",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/syzygy.py#L1809-L1915 |
224,844 | niklasf/python-chess | chess/pgn.py | GameNode.board | def board(self, *, _cache: bool = True) -> chess.Board:
"""
Gets a board with the position of the node.
It's a copy, so modifying the board will not alter the game.
"""
if self.board_cached is not None:
board = self.board_cached()
if board is not None:
return board.copy()
board = self.parent.board(_cache=False)
board.push(self.move)
if _cache:
self.board_cached = weakref.ref(board)
return board.copy()
else:
return board | python | def board(self, *, _cache: bool = True) -> chess.Board:
"""
Gets a board with the position of the node.
It's a copy, so modifying the board will not alter the game.
"""
if self.board_cached is not None:
board = self.board_cached()
if board is not None:
return board.copy()
board = self.parent.board(_cache=False)
board.push(self.move)
if _cache:
self.board_cached = weakref.ref(board)
return board.copy()
else:
return board | [
"def",
"board",
"(",
"self",
",",
"*",
",",
"_cache",
":",
"bool",
"=",
"True",
")",
"->",
"chess",
".",
"Board",
":",
"if",
"self",
".",
"board_cached",
"is",
"not",
"None",
":",
"board",
"=",
"self",
".",
"board_cached",
"(",
")",
"if",
"board",
... | Gets a board with the position of the node.
It's a copy, so modifying the board will not alter the game. | [
"Gets",
"a",
"board",
"with",
"the",
"position",
"of",
"the",
"node",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L139-L157 |
224,845 | niklasf/python-chess | chess/pgn.py | GameNode.root | def root(self) -> "GameNode":
"""Gets the root node, i.e., the game."""
node = self
while node.parent:
node = node.parent
return node | python | def root(self) -> "GameNode":
"""Gets the root node, i.e., the game."""
node = self
while node.parent:
node = node.parent
return node | [
"def",
"root",
"(",
"self",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
":",
"node",
"=",
"node",
".",
"parent",
"return",
"node"
] | Gets the root node, i.e., the game. | [
"Gets",
"the",
"root",
"node",
"i",
".",
"e",
".",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L177-L184 |
224,846 | niklasf/python-chess | chess/pgn.py | GameNode.end | def end(self) -> "GameNode":
"""Follows the main variation to the end and returns the last node."""
node = self
while node.variations:
node = node.variations[0]
return node | python | def end(self) -> "GameNode":
"""Follows the main variation to the end and returns the last node."""
node = self
while node.variations:
node = node.variations[0]
return node | [
"def",
"end",
"(",
"self",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
"while",
"node",
".",
"variations",
":",
"node",
"=",
"node",
".",
"variations",
"[",
"0",
"]",
"return",
"node"
] | Follows the main variation to the end and returns the last node. | [
"Follows",
"the",
"main",
"variation",
"to",
"the",
"end",
"and",
"returns",
"the",
"last",
"node",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L186-L193 |
224,847 | niklasf/python-chess | chess/pgn.py | GameNode.is_mainline | def is_mainline(self) -> bool:
"""Checks if the node is in the mainline of the game."""
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True | python | def is_mainline(self) -> bool:
"""Checks if the node is in the mainline of the game."""
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True | [
"def",
"is_mainline",
"(",
"self",
")",
"->",
"bool",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
":",
"parent",
"=",
"node",
".",
"parent",
"if",
"not",
"parent",
".",
"variations",
"or",
"parent",
".",
"variations",
"[",
"0",
"]",
"!=... | Checks if the node is in the mainline of the game. | [
"Checks",
"if",
"the",
"node",
"is",
"in",
"the",
"mainline",
"of",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L213-L225 |
224,848 | niklasf/python-chess | chess/pgn.py | GameNode.is_main_variation | def is_main_variation(self) -> bool:
"""
Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation.
"""
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self | python | def is_main_variation(self) -> bool:
"""
Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation.
"""
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self | [
"def",
"is_main_variation",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"True",
"return",
"not",
"self",
".",
"parent",
".",
"variations",
"or",
"self",
".",
"parent",
".",
"variations",
"[",
"0",
"]",
"==",
... | Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation. | [
"Checks",
"if",
"this",
"node",
"is",
"the",
"first",
"variation",
"from",
"the",
"point",
"of",
"view",
"of",
"its",
"parent",
".",
"The",
"root",
"node",
"is",
"also",
"in",
"the",
"main",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L227-L235 |
224,849 | niklasf/python-chess | chess/pgn.py | GameNode.promote | def promote(self, move: chess.Move) -> None:
"""Moves a variation one up in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | python | def promote(self, move: chess.Move) -> None:
"""Moves a variation one up in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | [
"def",
"promote",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"variation",
"=",
"self",
"[",
"move",
"]",
"i",
"=",
"self",
".",
"variations",
".",
"index",
"(",
"variation",
")",
"if",
"i",
">",
"0",
":",
"self",... | Moves a variation one up in the list of variations. | [
"Moves",
"a",
"variation",
"one",
"up",
"in",
"the",
"list",
"of",
"variations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L263-L268 |
224,850 | niklasf/python-chess | chess/pgn.py | GameNode.demote | def demote(self, move: chess.Move) -> None:
"""Moves a variation one down in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] | python | def demote(self, move: chess.Move) -> None:
"""Moves a variation one down in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] | [
"def",
"demote",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"variation",
"=",
"self",
"[",
"move",
"]",
"i",
"=",
"self",
".",
"variations",
".",
"index",
"(",
"variation",
")",
"if",
"i",
"<",
"len",
"(",
"self"... | Moves a variation one down in the list of variations. | [
"Moves",
"a",
"variation",
"one",
"down",
"in",
"the",
"list",
"of",
"variations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L270-L275 |
224,851 | niklasf/python-chess | chess/pgn.py | GameNode.remove_variation | def remove_variation(self, move: chess.Move) -> None:
"""Removes a variation."""
self.variations.remove(self.variation(move)) | python | def remove_variation(self, move: chess.Move) -> None:
"""Removes a variation."""
self.variations.remove(self.variation(move)) | [
"def",
"remove_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"self",
".",
"variations",
".",
"remove",
"(",
"self",
".",
"variation",
"(",
"move",
")",
")"
] | Removes a variation. | [
"Removes",
"a",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L277-L279 |
224,852 | niklasf/python-chess | chess/pgn.py | GameNode.add_variation | def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
"""Creates a child node with the given attributes."""
node = type(self).dangling_node()
node.move = move
node.nags = set(nags)
node.comment = comment
node.starting_comment = starting_comment
node.parent = self
self.variations.append(node)
return node | python | def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
"""Creates a child node with the given attributes."""
node = type(self).dangling_node()
node.move = move
node.nags = set(nags)
node.comment = comment
node.starting_comment = starting_comment
node.parent = self
self.variations.append(node)
return node | [
"def",
"add_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
",",
"*",
",",
"comment",
":",
"str",
"=",
"\"\"",
",",
"starting_comment",
":",
"str",
"=",
"\"\"",
",",
"nags",
":",
"Iterable",
"[",
"int",
"]",
"=",
"(",
")",
")",
"... | Creates a child node with the given attributes. | [
"Creates",
"a",
"child",
"node",
"with",
"the",
"given",
"attributes",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L281-L291 |
224,853 | niklasf/python-chess | chess/pgn.py | GameNode.add_main_variation | def add_main_variation(self, move: chess.Move, *, comment: str = "") -> "GameNode":
"""
Creates a child node with the given attributes and promotes it to the
main variation.
"""
node = self.add_variation(move, comment=comment)
self.variations.remove(node)
self.variations.insert(0, node)
return node | python | def add_main_variation(self, move: chess.Move, *, comment: str = "") -> "GameNode":
"""
Creates a child node with the given attributes and promotes it to the
main variation.
"""
node = self.add_variation(move, comment=comment)
self.variations.remove(node)
self.variations.insert(0, node)
return node | [
"def",
"add_main_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
",",
"*",
",",
"comment",
":",
"str",
"=",
"\"\"",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
".",
"add_variation",
"(",
"move",
",",
"comment",
"=",
"comment",... | Creates a child node with the given attributes and promotes it to the
main variation. | [
"Creates",
"a",
"child",
"node",
"with",
"the",
"given",
"attributes",
"and",
"promotes",
"it",
"to",
"the",
"main",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L293-L301 |
224,854 | niklasf/python-chess | chess/pgn.py | Game.board | def board(self, *, _cache: bool = False) -> chess.Board:
"""
Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``).
"""
return self.headers.board() | python | def board(self, *, _cache: bool = False) -> chess.Board:
"""
Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``).
"""
return self.headers.board() | [
"def",
"board",
"(",
"self",
",",
"*",
",",
"_cache",
":",
"bool",
"=",
"False",
")",
"->",
"chess",
".",
"Board",
":",
"return",
"self",
".",
"headers",
".",
"board",
"(",
")"
] | Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``). | [
"Gets",
"the",
"starting",
"position",
"of",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L432-L439 |
224,855 | niklasf/python-chess | chess/pgn.py | BaseVisitor.parse_san | def parse_san(self, board: chess.Board, san: str) -> chess.Move:
"""
When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format.
"""
# Replace zeros with correct castling notation.
if san == "0-0":
san = "O-O"
elif san == "0-0-0":
san = "O-O-O"
return board.parse_san(san) | python | def parse_san(self, board: chess.Board, san: str) -> chess.Move:
"""
When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format.
"""
# Replace zeros with correct castling notation.
if san == "0-0":
san = "O-O"
elif san == "0-0-0":
san = "O-O-O"
return board.parse_san(san) | [
"def",
"parse_san",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
",",
"san",
":",
"str",
")",
"->",
"chess",
".",
"Move",
":",
"# Replace zeros with correct castling notation.",
"if",
"san",
"==",
"\"0-0\"",
":",
"san",
"=",
"\"O-O\"",
"elif",
"s... | When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format. | [
"When",
"the",
"visitor",
"is",
"used",
"by",
"a",
"parser",
"this",
"is",
"called",
"to",
"parse",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L710-L724 |
224,856 | niklasf/python-chess | setup.py | read_description | def read_description():
"""
Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number.
"""
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f:
description = f.read()
# Link to the documentation of the specific version.
description = description.replace(
"//python-chess.readthedocs.io/en/latest/",
"//python-chess.readthedocs.io/en/v{}/".format(chess.__version__))
# Use documentation badge for the specific version.
description = description.replace(
"//readthedocs.org/projects/python-chess/badge/?version=latest",
"//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__))
# Show Travis CI build status of the concrete version.
description = description.replace(
"//travis-ci.org/niklasf/python-chess.svg?branch=master",
"//travis-ci.org/niklasf/python-chess.svg?branch=v{}".format(chess.__version__))
# Show Appveyor build status of the concrete version.
description = description.replace(
"/y9k3hdbm0f0nbum9/branch/master",
"/y9k3hdbm0f0nbum9/branch/v{}".format(chess.__version__))
# Remove doctest comments.
description = re.sub(r"\s*# doctest:.*", "", description)
return description | python | def read_description():
"""
Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number.
"""
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f:
description = f.read()
# Link to the documentation of the specific version.
description = description.replace(
"//python-chess.readthedocs.io/en/latest/",
"//python-chess.readthedocs.io/en/v{}/".format(chess.__version__))
# Use documentation badge for the specific version.
description = description.replace(
"//readthedocs.org/projects/python-chess/badge/?version=latest",
"//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__))
# Show Travis CI build status of the concrete version.
description = description.replace(
"//travis-ci.org/niklasf/python-chess.svg?branch=master",
"//travis-ci.org/niklasf/python-chess.svg?branch=v{}".format(chess.__version__))
# Show Appveyor build status of the concrete version.
description = description.replace(
"/y9k3hdbm0f0nbum9/branch/master",
"/y9k3hdbm0f0nbum9/branch/v{}".format(chess.__version__))
# Remove doctest comments.
description = re.sub(r"\s*# doctest:.*", "", description)
return description | [
"def",
"read_description",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"README.rst\"",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"descript... | Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number. | [
"Reads",
"the",
"description",
"from",
"README",
".",
"rst",
"and",
"substitutes",
"mentions",
"of",
"the",
"latest",
"version",
"with",
"a",
"concrete",
"version",
"number",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/setup.py#L40-L71 |
224,857 | niklasf/python-chess | chess/engine.py | popen_uci | async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
"""
Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | python | async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
"""
Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | [
"async",
"def",
"popen_uci",
"(",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"setpgrp",
":",
"bool",
"=",
"False",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"popen_args",
":",
"Any",
")",
"->",
"Tuple",
... | Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair. | [
"Spawns",
"and",
"initializes",
"an",
"UCI",
"engine",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2158-L2180 |
224,858 | niklasf/python-chess | chess/engine.py | popen_xboard | async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]:
"""
Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | python | async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]:
"""
Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | [
"async",
"def",
"popen_xboard",
"(",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"setpgrp",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"popen_args",
":",
"Any",
")",
"->",
"Tuple",
"[",
"asyncio",
".",
"S... | Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair. | [
"Spawns",
"and",
"initializes",
"an",
"XBoard",
"engine",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2183-L2205 |
224,859 | niklasf/python-chess | chess/engine.py | UciProtocol.debug | def debug(self, on: bool = True) -> None:
"""
Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations.
"""
if on:
self.send_line("debug on")
else:
self.send_line("debug off") | python | def debug(self, on: bool = True) -> None:
"""
Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations.
"""
if on:
self.send_line("debug on")
else:
self.send_line("debug off") | [
"def",
"debug",
"(",
"self",
",",
"on",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"on",
":",
"self",
".",
"send_line",
"(",
"\"debug on\"",
")",
"else",
":",
"self",
".",
"send_line",
"(",
"\"debug off\"",
")"
] | Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations. | [
"Switches",
"debug",
"mode",
"of",
"the",
"engine",
"on",
"or",
"off",
".",
"This",
"does",
"not",
"interrupt",
"other",
"ongoing",
"operations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L1024-L1032 |
224,860 | niklasf/python-chess | chess/engine.py | AnalysisResult.stop | def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | python | def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stop",
"and",
"not",
"self",
".",
"_posted_kork",
":",
"self",
".",
"_stop",
"(",
")",
"self",
".",
"_stop",
"=",
"None"
] | Stops the analysis as soon as possible. | [
"Stops",
"the",
"analysis",
"as",
"soon",
"as",
"possible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2090-L2094 |
224,861 | niklasf/python-chess | chess/engine.py | AnalysisResult.get | async def get(self) -> InfoDict:
"""
Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception.
"""
if self._seen_kork:
raise AnalysisComplete()
info = await self._queue.get()
if not info:
# Empty dictionary marks end.
self._seen_kork = True
await self._finished
raise AnalysisComplete()
return info | python | async def get(self) -> InfoDict:
"""
Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception.
"""
if self._seen_kork:
raise AnalysisComplete()
info = await self._queue.get()
if not info:
# Empty dictionary marks end.
self._seen_kork = True
await self._finished
raise AnalysisComplete()
return info | [
"async",
"def",
"get",
"(",
"self",
")",
"->",
"InfoDict",
":",
"if",
"self",
".",
"_seen_kork",
":",
"raise",
"AnalysisComplete",
"(",
")",
"info",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"not",
"info",
":",
"# Empty dictionar... | Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception. | [
"Waits",
"for",
"the",
"next",
"dictionary",
"of",
"information",
"from",
"the",
"engine",
"and",
"returns",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2100-L2122 |
224,862 | niklasf/python-chess | chess/engine.py | AnalysisResult.empty | def empty(self) -> bool:
"""
Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly.
"""
return self._seen_kork or self._queue.qsize() <= self._posted_kork | python | def empty(self) -> bool:
"""
Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly.
"""
return self._seen_kork or self._queue.qsize() <= self._posted_kork | [
"def",
"empty",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_seen_kork",
"or",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
"<=",
"self",
".",
"_posted_kork"
] | Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly. | [
"Checks",
"if",
"all",
"information",
"has",
"been",
"consumed",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2124-L2134 |
224,863 | niklasf/python-chess | chess/engine.py | SimpleEngine.close | def close(self) -> None:
"""
Closes the transport and the background event loop as soon as possible.
"""
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
self._shutdown = True
self.protocol.loop.call_soon_threadsafe(_shutdown) | python | def close(self) -> None:
"""
Closes the transport and the background event loop as soon as possible.
"""
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
self._shutdown = True
self.protocol.loop.call_soon_threadsafe(_shutdown) | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"def",
"_shutdown",
"(",
")",
"->",
"None",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"shutdown_event",
".",
"set",
"(",
")",
"with",
"self",
".",
"_shutdown_lock",
":",
... | Closes the transport and the background event loop as soon as possible. | [
"Closes",
"the",
"transport",
"and",
"the",
"background",
"event",
"loop",
"as",
"soon",
"as",
"possible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2314-L2325 |
224,864 | niklasf/python-chess | chess/gaviota.py | open_tablebase_native | def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used.
"""
libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1"
tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb))
tables.add_directory(directory)
return tables | python | def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used.
"""
libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1"
tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb))
tables.add_directory(directory)
return tables | [
"def",
"open_tablebase_native",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"libgtb",
":",
"Any",
"=",
"None",
",",
"LibraryLoader",
":",
"Any",
"=",
"ctypes",
".",
"cdll",
")",
"->",
"NativeTablebase",
":",
"libgtb",
"=",
"libgtb",
"or",
"ctypes",
... | Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used. | [
"Opens",
"a",
"collection",
"of",
"tables",
"for",
"probing",
"using",
"libgtb",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L2083-L2096 |
224,865 | niklasf/python-chess | chess/gaviota.py | open_tablebase | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
"""
Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried.
"""
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
LOGGER.info("Falling back to pure Python tablebase: %r", err)
tables = PythonTablebase()
tables.add_directory(directory)
return tables | python | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
"""
Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried.
"""
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
LOGGER.info("Falling back to pure Python tablebase: %r", err)
tables = PythonTablebase()
tables.add_directory(directory)
return tables | [
"def",
"open_tablebase",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"libgtb",
":",
"Any",
"=",
"None",
",",
"LibraryLoader",
":",
"Any",
"=",
"ctypes",
".",
"cdll",
")",
"->",
"Union",
"[",
"NativeTablebase",
",",
"PythonTablebase",
"]",
":",
"try... | Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried. | [
"Opens",
"a",
"collection",
"of",
"tables",
"for",
"probing",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L2099-L2118 |
224,866 | niklasf/python-chess | chess/gaviota.py | PythonTablebase.probe_dtm | def probe_dtm(self, board: chess.Board) -> int:
"""
Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior.
"""
# Can not probe positions with castling rights.
if board.castling_rights:
raise KeyError("gaviota tables do not contain positions with castling rights: {}".format(board.fen()))
# Supports only up to 5 pieces.
if chess.popcount(board.occupied) > 5:
raise KeyError("gaviota tables support up to 5 pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# KvK is a draw.
if board.occupied == board.kings:
return 0
# Prepare the tablebase request.
white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE]))
white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares]
black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK]))
black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares]
side = 0 if (board.turn == chess.WHITE) else 1
epsq = board.ep_square if board.ep_square else NOSQUARE
req = Request(white_squares, white_types, black_squares, black_types, side, epsq)
# Probe.
dtm = self.egtb_get_dtm(req)
ply, res = unpackdist(dtm)
if res == iWMATE:
# White mates in the stored position.
if req.realside == 1:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
elif res == iBMATE:
# Black mates in the stored position.
if req.realside == 0:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
else:
# Draw.
return 0 | python | def probe_dtm(self, board: chess.Board) -> int:
"""
Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior.
"""
# Can not probe positions with castling rights.
if board.castling_rights:
raise KeyError("gaviota tables do not contain positions with castling rights: {}".format(board.fen()))
# Supports only up to 5 pieces.
if chess.popcount(board.occupied) > 5:
raise KeyError("gaviota tables support up to 5 pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# KvK is a draw.
if board.occupied == board.kings:
return 0
# Prepare the tablebase request.
white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE]))
white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares]
black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK]))
black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares]
side = 0 if (board.turn == chess.WHITE) else 1
epsq = board.ep_square if board.ep_square else NOSQUARE
req = Request(white_squares, white_types, black_squares, black_types, side, epsq)
# Probe.
dtm = self.egtb_get_dtm(req)
ply, res = unpackdist(dtm)
if res == iWMATE:
# White mates in the stored position.
if req.realside == 1:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
elif res == iBMATE:
# Black mates in the stored position.
if req.realside == 0:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
else:
# Draw.
return 0 | [
"def",
"probe_dtm",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
")",
"->",
"int",
":",
"# Can not probe positions with castling rights.",
"if",
"board",
".",
"castling_rights",
":",
"raise",
"KeyError",
"(",
"\"gaviota tables do not contain positions with cas... | Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior. | [
"Probes",
"for",
"depth",
"to",
"mate",
"information",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L1556-L1633 |
224,867 | niklasf/python-chess | chess/__init__.py | Piece.symbol | def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces.
"""
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol | python | def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces.
"""
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol | [
"def",
"symbol",
"(",
"self",
")",
"->",
"str",
":",
"symbol",
"=",
"piece_symbol",
"(",
"self",
".",
"piece_type",
")",
"return",
"symbol",
".",
"upper",
"(",
")",
"if",
"self",
".",
"color",
"else",
"symbol"
] | Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces. | [
"Gets",
"the",
"symbol",
"P",
"N",
"B",
"R",
"Q",
"or",
"K",
"for",
"white",
"pieces",
"or",
"the",
"lower",
"-",
"case",
"variants",
"for",
"the",
"black",
"pieces",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L394-L400 |
224,868 | niklasf/python-chess | chess/__init__.py | Piece.unicode_symbol | def unicode_symbol(self, *, invert_color: bool = False) -> str:
"""
Gets the Unicode character for the piece.
"""
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol] | python | def unicode_symbol(self, *, invert_color: bool = False) -> str:
"""
Gets the Unicode character for the piece.
"""
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol] | [
"def",
"unicode_symbol",
"(",
"self",
",",
"*",
",",
"invert_color",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"symbol",
"=",
"self",
".",
"symbol",
"(",
")",
".",
"swapcase",
"(",
")",
"if",
"invert_color",
"else",
"self",
".",
"symbol",
"("... | Gets the Unicode character for the piece. | [
"Gets",
"the",
"Unicode",
"character",
"for",
"the",
"piece",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L402-L407 |
224,869 | niklasf/python-chess | chess/__init__.py | Move.uci | def uci(self) -> str:
"""
Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``.
"""
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000" | python | def uci(self) -> str:
"""
Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``.
"""
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000" | [
"def",
"uci",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"drop",
":",
"return",
"piece_symbol",
"(",
"self",
".",
"drop",
")",
".",
"upper",
"(",
")",
"+",
"\"@\"",
"+",
"SQUARE_NAMES",
"[",
"self",
".",
"to_square",
"]",
"elif",
"self"... | Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``. | [
"Gets",
"an",
"UCI",
"string",
"for",
"the",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L452-L468 |
224,870 | niklasf/python-chess | chess/__init__.py | Move.from_uci | def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif len(uci) == 4:
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))
elif len(uci) == 5:
promotion = PIECE_SYMBOLS.index(uci[4])
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci)) | python | def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif len(uci) == 4:
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))
elif len(uci) == 5:
promotion = PIECE_SYMBOLS.index(uci[4])
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci)) | [
"def",
"from_uci",
"(",
"cls",
",",
"uci",
":",
"str",
")",
"->",
"\"Move\"",
":",
"if",
"uci",
"==",
"\"0000\"",
":",
"return",
"cls",
".",
"null",
"(",
")",
"elif",
"len",
"(",
"uci",
")",
"==",
"4",
"and",
"\"@\"",
"==",
"uci",
"[",
"1",
"]"... | Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid. | [
"Parses",
"an",
"UCI",
"string",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L504-L522 |
224,871 | niklasf/python-chess | chess/__init__.py | BaseBoard.pieces | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color)) | python | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color)) | [
"def",
"pieces",
"(",
"self",
",",
"piece_type",
":",
"PieceType",
",",
"color",
":",
"Color",
")",
"->",
"\"SquareSet\"",
":",
"return",
"SquareSet",
"(",
"self",
".",
"pieces_mask",
"(",
"piece_type",
",",
"color",
")",
")"
] | Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`. | [
"Gets",
"pieces",
"of",
"the",
"given",
"type",
"and",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L614-L620 |
224,872 | niklasf/python-chess | chess/__init__.py | BaseBoard.piece_type_at | def piece_type_at(self, square: Square) -> Optional[PieceType]:
"""Gets the piece type at the given square."""
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.queens & mask:
return QUEEN
else:
return KING | python | def piece_type_at(self, square: Square) -> Optional[PieceType]:
"""Gets the piece type at the given square."""
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.queens & mask:
return QUEEN
else:
return KING | [
"def",
"piece_type_at",
"(",
"self",
",",
"square",
":",
"Square",
")",
"->",
"Optional",
"[",
"PieceType",
"]",
":",
"mask",
"=",
"BB_SQUARES",
"[",
"square",
"]",
"if",
"not",
"self",
".",
"occupied",
"&",
"mask",
":",
"return",
"None",
"# Early return... | Gets the piece type at the given square. | [
"Gets",
"the",
"piece",
"type",
"at",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L632-L649 |
224,873 | niklasf/python-chess | chess/__init__.py | BaseBoard.king | def king(self, color: Color) -> Optional[Square]:
"""
Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered.
"""
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
return msb(king_mask) if king_mask else None | python | def king(self, color: Color) -> Optional[Square]:
"""
Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered.
"""
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
return msb(king_mask) if king_mask else None | [
"def",
"king",
"(",
"self",
",",
"color",
":",
"Color",
")",
"->",
"Optional",
"[",
"Square",
"]",
":",
"king_mask",
"=",
"self",
".",
"occupied_co",
"[",
"color",
"]",
"&",
"self",
".",
"kings",
"&",
"~",
"self",
".",
"promoted",
"return",
"msb",
... | Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered. | [
"Finds",
"the",
"king",
"square",
"of",
"the",
"given",
"side",
".",
"Returns",
"None",
"if",
"there",
"is",
"no",
"king",
"of",
"that",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L651-L660 |
224,874 | niklasf/python-chess | chess/__init__.py | BaseBoard.is_attacked_by | def is_attacked_by(self, color: Color, square: Square) -> bool:
"""
Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked.
"""
return bool(self.attackers_mask(color, square)) | python | def is_attacked_by(self, color: Color, square: Square) -> bool:
"""
Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked.
"""
return bool(self.attackers_mask(color, square)) | [
"def",
"is_attacked_by",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"attackers_mask",
"(",
"color",
",",
"square",
")",
")"
] | Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked. | [
"Checks",
"if",
"the",
"given",
"side",
"attacks",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L713-L720 |
224,875 | niklasf/python-chess | chess/__init__.py | BaseBoard.attackers | def attackers(self, color: Color, square: Square) -> "SquareSet":
"""
Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attackers_mask(color, square)) | python | def attackers(self, color: Color, square: Square) -> "SquareSet":
"""
Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attackers_mask(color, square)) | [
"def",
"attackers",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"\"SquareSet\"",
":",
"return",
"SquareSet",
"(",
"self",
".",
"attackers_mask",
"(",
"color",
",",
"square",
")",
")"
] | Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`. | [
"Gets",
"a",
"set",
"of",
"attackers",
"of",
"the",
"given",
"color",
"for",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L722-L730 |
224,876 | niklasf/python-chess | chess/__init__.py | BaseBoard.is_pinned | def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL | python | def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL | [
"def",
"is_pinned",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"self",
".",
"pin_mask",
"(",
"color",
",",
"square",
")",
"!=",
"BB_ALL"
] | Detects if the given square is pinned to the king of the given color. | [
"Detects",
"if",
"the",
"given",
"square",
"is",
"pinned",
"to",
"the",
"king",
"of",
"the",
"given",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L782-L786 |
224,877 | niklasf/python-chess | chess/__init__.py | BaseBoard.set_piece_at | def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
"""
Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`.
"""
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted) | python | def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
"""
Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`.
"""
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted) | [
"def",
"set_piece_at",
"(",
"self",
",",
"square",
":",
"Square",
",",
"piece",
":",
"Optional",
"[",
"Piece",
"]",
",",
"promoted",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"piece",
"is",
"None",
":",
"self",
".",
"_remove_piece_at",
... | Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`. | [
"Sets",
"a",
"piece",
"at",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L850-L860 |
224,878 | niklasf/python-chess | chess/__init__.py | BaseBoard.board_fen | def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder) | python | def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder) | [
"def",
"board_fen",
"(",
"self",
",",
"*",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"False",
")",
"->",
"str",
":",
"builder",
"=",
"[",
"]",
"empty",
"=",
"0",
"for",
"square",
"in",
"SQUARES_180",
":",
"piece",
"=",
"self",
".",
... | Gets the board FEN. | [
"Gets",
"the",
"board",
"FEN",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L862-L890 |
224,879 | niklasf/python-chess | chess/__init__.py | BaseBoard.chess960_pos | def chess960_pos(self) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 959
or ``None``.
"""
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return None
if self.pawns != BB_RANK_2 | BB_RANK_7:
return None
if self.promoted:
return None
# Piece counts.
brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings]
if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]:
return None
# Symmetry.
if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk):
return None
# Algorithm from ChessX, src/database/bitboard.cpp, r2254.
x = self.bishops & (2 + 8 + 32 + 128)
if not x:
return None
bs1 = (lsb(x) - 1) // 2
cc_pos = bs1
x = self.bishops & (1 + 4 + 16 + 64)
if not x:
return None
bs2 = lsb(x) * 2
cc_pos += bs2
q = 0
qf = False
n0 = 0
n1 = 0
n0f = False
n1f = False
rf = 0
n0s = [0, 4, 7, 9]
for square in range(A1, H1 + 1):
bb = BB_SQUARES[square]
if bb & self.queens:
qf = True
elif bb & self.rooks or bb & self.kings:
if bb & self.kings:
if rf != 1:
return None
else:
rf += 1
if not qf:
q += 1
if not n0f:
n0 += 1
elif not n1f:
n1 += 1
elif bb & self.knights:
if not qf:
q += 1
if not n0f:
n0f = True
elif not n1f:
n1f = True
if n0 < 4 and n1f and qf:
cc_pos += q * 16
krn = n0s[n0] + n1
cc_pos += krn * 96
return cc_pos
else:
return None | python | def chess960_pos(self) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 959
or ``None``.
"""
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return None
if self.pawns != BB_RANK_2 | BB_RANK_7:
return None
if self.promoted:
return None
# Piece counts.
brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings]
if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]:
return None
# Symmetry.
if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk):
return None
# Algorithm from ChessX, src/database/bitboard.cpp, r2254.
x = self.bishops & (2 + 8 + 32 + 128)
if not x:
return None
bs1 = (lsb(x) - 1) // 2
cc_pos = bs1
x = self.bishops & (1 + 4 + 16 + 64)
if not x:
return None
bs2 = lsb(x) * 2
cc_pos += bs2
q = 0
qf = False
n0 = 0
n1 = 0
n0f = False
n1f = False
rf = 0
n0s = [0, 4, 7, 9]
for square in range(A1, H1 + 1):
bb = BB_SQUARES[square]
if bb & self.queens:
qf = True
elif bb & self.rooks or bb & self.kings:
if bb & self.kings:
if rf != 1:
return None
else:
rf += 1
if not qf:
q += 1
if not n0f:
n0 += 1
elif not n1f:
n1 += 1
elif bb & self.knights:
if not qf:
q += 1
if not n0f:
n0f = True
elif not n1f:
n1f = True
if n0 < 4 and n1f and qf:
cc_pos += q * 16
krn = n0s[n0] + n1
cc_pos += krn * 96
return cc_pos
else:
return None | [
"def",
"chess960_pos",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",
".",
"occupied_co",
"[",
"WHITE",
"]",
"!=",
"BB_RANK_1",
"|",
"BB_RANK_2",
":",
"return",
"None",
"if",
"self",
".",
"occupied_co",
"[",
"BLACK",
"]",
"!=",... | Gets the Chess960 starting position index between 0 and 959
or ``None``. | [
"Gets",
"the",
"Chess960",
"starting",
"position",
"index",
"between",
"0",
"and",
"959",
"or",
"None",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1043-L1119 |
224,880 | niklasf/python-chess | chess/__init__.py | BaseBoard.mirror | def mirror(self: BaseBoardT) -> BaseBoardT:
"""
Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color.
"""
board = self.transform(flip_vertical)
board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]
return board | python | def mirror(self: BaseBoardT) -> BaseBoardT:
"""
Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color.
"""
board = self.transform(flip_vertical)
board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]
return board | [
"def",
"mirror",
"(",
"self",
":",
"BaseBoardT",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"self",
".",
"transform",
"(",
"flip_vertical",
")",
"board",
".",
"occupied_co",
"[",
"WHITE",
"]",
",",
"board",
".",
"occupied_co",
"[",
"BLACK",
"]",
"=",
... | Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color. | [
"Returns",
"a",
"mirrored",
"copy",
"of",
"the",
"board",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1226-L1235 |
224,881 | niklasf/python-chess | chess/__init__.py | BaseBoard.from_chess960_pos | def from_chess960_pos(cls: Type[BaseBoardT], sharnagl: int) -> BaseBoardT:
"""
Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))
"""
board = cls.empty()
board.set_chess960_pos(sharnagl)
return board | python | def from_chess960_pos(cls: Type[BaseBoardT], sharnagl: int) -> BaseBoardT:
"""
Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))
"""
board = cls.empty()
board.set_chess960_pos(sharnagl)
return board | [
"def",
"from_chess960_pos",
"(",
"cls",
":",
"Type",
"[",
"BaseBoardT",
"]",
",",
"sharnagl",
":",
"int",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"cls",
".",
"empty",
"(",
")",
"board",
".",
"set_chess960_pos",
"(",
"sharnagl",
")",
"return",
"board"... | Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959)) | [
"Creates",
"a",
"new",
"board",
"initialized",
"with",
"a",
"Chess960",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1272-L1283 |
224,882 | niklasf/python-chess | chess/__init__.py | Board.reset | def reset(self) -> None:
"""Restores the starting position."""
self.turn = WHITE
self.castling_rights = BB_CORNERS
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.reset_board() | python | def reset(self) -> None:
"""Restores the starting position."""
self.turn = WHITE
self.castling_rights = BB_CORNERS
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.reset_board() | [
"def",
"reset",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"turn",
"=",
"WHITE",
"self",
".",
"castling_rights",
"=",
"BB_CORNERS",
"self",
".",
"ep_square",
"=",
"None",
"self",
".",
"halfmove_clock",
"=",
"0",
"self",
".",
"fullmove_number",
"="... | Restores the starting position. | [
"Restores",
"the",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1394-L1402 |
224,883 | niklasf/python-chess | chess/__init__.py | Board.clear | def clear(self) -> None:
"""
Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board.
"""
self.turn = WHITE
self.castling_rights = BB_EMPTY
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.clear_board() | python | def clear(self) -> None:
"""
Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board.
"""
self.turn = WHITE
self.castling_rights = BB_EMPTY
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.clear_board() | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"turn",
"=",
"WHITE",
"self",
".",
"castling_rights",
"=",
"BB_EMPTY",
"self",
".",
"ep_square",
"=",
"None",
"self",
".",
"halfmove_clock",
"=",
"0",
"self",
".",
"fullmove_number",
"=",
... | Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board. | [
"Clears",
"the",
"board",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1408-L1424 |
224,884 | niklasf/python-chess | chess/__init__.py | Board.root | def root(self: BoardT) -> BoardT:
"""Returns a copy of the root position."""
if self._stack:
board = type(self)(None, chess960=self.chess960)
self._stack[0].restore(board)
return board
else:
return self.copy(stack=False) | python | def root(self: BoardT) -> BoardT:
"""Returns a copy of the root position."""
if self._stack:
board = type(self)(None, chess960=self.chess960)
self._stack[0].restore(board)
return board
else:
return self.copy(stack=False) | [
"def",
"root",
"(",
"self",
":",
"BoardT",
")",
"->",
"BoardT",
":",
"if",
"self",
".",
"_stack",
":",
"board",
"=",
"type",
"(",
"self",
")",
"(",
"None",
",",
"chess960",
"=",
"self",
".",
"chess960",
")",
"self",
".",
"_stack",
"[",
"0",
"]",
... | Returns a copy of the root position. | [
"Returns",
"a",
"copy",
"of",
"the",
"root",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1435-L1442 |
224,885 | niklasf/python-chess | chess/__init__.py | Board.is_check | def is_check(self) -> bool:
"""Returns if the current side to move is in check."""
king = self.king(self.turn)
return king is not None and self.is_attacked_by(not self.turn, king) | python | def is_check(self) -> bool:
"""Returns if the current side to move is in check."""
king = self.king(self.turn)
return king is not None and self.is_attacked_by(not self.turn, king) | [
"def",
"is_check",
"(",
"self",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"self",
".",
"turn",
")",
"return",
"king",
"is",
"not",
"None",
"and",
"self",
".",
"is_attacked_by",
"(",
"not",
"self",
".",
"turn",
",",
"king",
")"
... | Returns if the current side to move is in check. | [
"Returns",
"if",
"the",
"current",
"side",
"to",
"move",
"is",
"in",
"check",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1540-L1543 |
224,886 | niklasf/python-chess | chess/__init__.py | Board.is_into_check | def is_into_check(self, move: Move) -> bool:
"""
Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal.
"""
king = self.king(self.turn)
if king is None:
return False
checkers = self.attackers_mask(not self.turn, king)
if checkers:
# If already in check, look if it is an evasion.
if move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]):
return True
return not self._is_safe(king, self._slider_blockers(king), move) | python | def is_into_check(self, move: Move) -> bool:
"""
Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal.
"""
king = self.king(self.turn)
if king is None:
return False
checkers = self.attackers_mask(not self.turn, king)
if checkers:
# If already in check, look if it is an evasion.
if move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]):
return True
return not self._is_safe(king, self._slider_blockers(king), move) | [
"def",
"is_into_check",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"self",
".",
"turn",
")",
"if",
"king",
"is",
"None",
":",
"return",
"False",
"checkers",
"=",
"self",
".",
"attackers_mask"... | Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal. | [
"Checks",
"if",
"the",
"given",
"move",
"would",
"leave",
"the",
"king",
"in",
"check",
"or",
"put",
"it",
"into",
"check",
".",
"The",
"move",
"must",
"be",
"at",
"least",
"pseudo",
"legal",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1545-L1560 |
224,887 | niklasf/python-chess | chess/__init__.py | Board.was_into_check | def was_into_check(self) -> bool:
"""
Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move.
"""
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king) | python | def was_into_check(self) -> bool:
"""
Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move.
"""
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king) | [
"def",
"was_into_check",
"(",
"self",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"not",
"self",
".",
"turn",
")",
"return",
"king",
"is",
"not",
"None",
"and",
"self",
".",
"is_attacked_by",
"(",
"self",
".",
"turn",
",",
"king",
... | Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move. | [
"Checks",
"if",
"the",
"king",
"of",
"the",
"other",
"side",
"is",
"attacked",
".",
"Such",
"a",
"position",
"is",
"not",
"valid",
"and",
"could",
"only",
"be",
"reached",
"by",
"an",
"illegal",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1562-L1568 |
224,888 | niklasf/python-chess | chess/__init__.py | Board.result | def result(self, *, claim_draw: bool = False) -> str:
"""
Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``.
"""
# Chess variant support.
if self.is_variant_loss():
return "0-1" if self.turn == WHITE else "1-0"
elif self.is_variant_win():
return "1-0" if self.turn == WHITE else "0-1"
elif self.is_variant_draw():
return "1/2-1/2"
# Checkmate.
if self.is_checkmate():
return "0-1" if self.turn == WHITE else "1-0"
# Draw claimed.
if claim_draw and self.can_claim_draw():
return "1/2-1/2"
# Seventyfive-move rule or fivefold repetition.
if self.is_seventyfive_moves() or self.is_fivefold_repetition():
return "1/2-1/2"
# Insufficient material.
if self.is_insufficient_material():
return "1/2-1/2"
# Stalemate.
if not any(self.generate_legal_moves()):
return "1/2-1/2"
# Undetermined.
return "*" | python | def result(self, *, claim_draw: bool = False) -> str:
"""
Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``.
"""
# Chess variant support.
if self.is_variant_loss():
return "0-1" if self.turn == WHITE else "1-0"
elif self.is_variant_win():
return "1-0" if self.turn == WHITE else "0-1"
elif self.is_variant_draw():
return "1/2-1/2"
# Checkmate.
if self.is_checkmate():
return "0-1" if self.turn == WHITE else "1-0"
# Draw claimed.
if claim_draw and self.can_claim_draw():
return "1/2-1/2"
# Seventyfive-move rule or fivefold repetition.
if self.is_seventyfive_moves() or self.is_fivefold_repetition():
return "1/2-1/2"
# Insufficient material.
if self.is_insufficient_material():
return "1/2-1/2"
# Stalemate.
if not any(self.generate_legal_moves()):
return "1/2-1/2"
# Undetermined.
return "*" | [
"def",
"result",
"(",
"self",
",",
"*",
",",
"claim_draw",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# Chess variant support.",
"if",
"self",
".",
"is_variant_loss",
"(",
")",
":",
"return",
"\"0-1\"",
"if",
"self",
".",
"turn",
"==",
"WHITE",
... | Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``. | [
"Gets",
"the",
"game",
"result",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1686-L1723 |
224,889 | niklasf/python-chess | chess/__init__.py | Board.is_stalemate | def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | python | def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | [
"def",
"is_stalemate",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"is_check",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"is_variant_end",
"(",
")",
":",
"return",
"False",
"return",
"not",
"any",
"(",
"self",
".",
"generate_lega... | Checks if the current position is a stalemate. | [
"Checks",
"if",
"the",
"current",
"position",
"is",
"a",
"stalemate",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1732-L1740 |
224,890 | niklasf/python-chess | chess/__init__.py | Board.can_claim_fifty_moves | def can_claim_fifty_moves(self) -> bool:
"""
Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make.
"""
# Fifty-move rule.
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False | python | def can_claim_fifty_moves(self) -> bool:
"""
Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make.
"""
# Fifty-move rule.
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False | [
"def",
"can_claim_fifty_moves",
"(",
"self",
")",
"->",
"bool",
":",
"# Fifty-move rule.",
"if",
"self",
".",
"halfmove_clock",
">=",
"100",
":",
"if",
"any",
"(",
"self",
".",
"generate_legal_moves",
"(",
")",
")",
":",
"return",
"True",
"return",
"False"
] | Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make. | [
"Draw",
"by",
"the",
"fifty",
"-",
"move",
"rule",
"can",
"be",
"claimed",
"once",
"the",
"clock",
"of",
"halfmoves",
"since",
"the",
"last",
"capture",
"or",
"pawn",
"move",
"becomes",
"equal",
"or",
"greater",
"to",
"100",
"and",
"the",
"side",
"to",
... | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1832-L1843 |
224,891 | niklasf/python-chess | chess/__init__.py | Board.can_claim_threefold_repetition | def can_claim_threefold_repetition(self) -> bool:
"""
Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table.
"""
transposition_key = self._transposition_key()
transpositions = collections.Counter() # type: typing.Counter[Hashable]
transpositions.update((transposition_key, ))
# Count positions.
switchyard = []
while self.move_stack:
move = self.pop()
switchyard.append(move)
if self.is_irreversible(move):
break
transpositions.update((self._transposition_key(), ))
while switchyard:
self.push(switchyard.pop())
# Threefold repetition occured.
if transpositions[transposition_key] >= 3:
return True
# The next legal move is a threefold repetition.
for move in self.generate_legal_moves():
self.push(move)
try:
if transpositions[self._transposition_key()] >= 2:
return True
finally:
self.pop()
return False | python | def can_claim_threefold_repetition(self) -> bool:
"""
Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table.
"""
transposition_key = self._transposition_key()
transpositions = collections.Counter() # type: typing.Counter[Hashable]
transpositions.update((transposition_key, ))
# Count positions.
switchyard = []
while self.move_stack:
move = self.pop()
switchyard.append(move)
if self.is_irreversible(move):
break
transpositions.update((self._transposition_key(), ))
while switchyard:
self.push(switchyard.pop())
# Threefold repetition occured.
if transpositions[transposition_key] >= 3:
return True
# The next legal move is a threefold repetition.
for move in self.generate_legal_moves():
self.push(move)
try:
if transpositions[self._transposition_key()] >= 2:
return True
finally:
self.pop()
return False | [
"def",
"can_claim_threefold_repetition",
"(",
"self",
")",
"->",
"bool",
":",
"transposition_key",
"=",
"self",
".",
"_transposition_key",
"(",
")",
"transpositions",
"=",
"collections",
".",
"Counter",
"(",
")",
"# type: typing.Counter[Hashable]",
"transpositions",
"... | Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table. | [
"Draw",
"by",
"threefold",
"repetition",
"can",
"be",
"claimed",
"if",
"the",
"position",
"on",
"the",
"board",
"occured",
"for",
"the",
"third",
"time",
"or",
"if",
"such",
"a",
"repetition",
"is",
"reached",
"with",
"one",
"of",
"the",
"possible",
"legal... | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1845-L1886 |
224,892 | niklasf/python-chess | chess/__init__.py | Board.pop | def pop(self: BoardT) -> Move:
"""
Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty.
"""
move = self.move_stack.pop()
self._stack.pop().restore(self)
return move | python | def pop(self: BoardT) -> Move:
"""
Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty.
"""
move = self.move_stack.pop()
self._stack.pop().restore(self)
return move | [
"def",
"pop",
"(",
"self",
":",
"BoardT",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"move_stack",
".",
"pop",
"(",
")",
"self",
".",
"_stack",
".",
"pop",
"(",
")",
".",
"restore",
"(",
"self",
")",
"return",
"move"
] | Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty. | [
"Restores",
"the",
"previous",
"position",
"and",
"returns",
"the",
"last",
"move",
"from",
"the",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2048-L2056 |
224,893 | niklasf/python-chess | chess/__init__.py | Board.fen | def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
"""
Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant.
"""
return " ".join([
self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),
str(self.halfmove_clock),
str(self.fullmove_number)
]) | python | def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
"""
Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant.
"""
return " ".join([
self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),
str(self.halfmove_clock),
str(self.fullmove_number)
]) | [
"def",
"fen",
"(",
"self",
",",
"*",
",",
"shredder",
":",
"bool",
"=",
"False",
",",
"en_passant",
":",
"str",
"=",
"\"legal\"",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"str",
":",
"return",
"\" \"",
".",
"join"... | Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant. | [
"Gets",
"a",
"FEN",
"representation",
"of",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2118-L2148 |
224,894 | niklasf/python-chess | chess/__init__.py | Board.set_fen | def set_fen(self, fen: str) -> None:
"""
Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid.
"""
parts = fen.split()
# Board part.
try:
board_part = parts.pop(0)
except IndexError:
raise ValueError("empty fen")
# Turn.
try:
turn_part = parts.pop(0)
except IndexError:
turn = WHITE
else:
if turn_part == "w":
turn = WHITE
elif turn_part == "b":
turn = BLACK
else:
raise ValueError("expected 'w' or 'b' for turn part of fen: {!r}".format(fen))
# Validate castling part.
try:
castling_part = parts.pop(0)
except IndexError:
castling_part = "-"
else:
if not FEN_CASTLING_REGEX.match(castling_part):
raise ValueError("invalid castling part in fen: {!r}".format(fen))
# En passant square.
try:
ep_part = parts.pop(0)
except IndexError:
ep_square = None
else:
try:
ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part)
except ValueError:
raise ValueError("invalid en passant part in fen: {!r}".format(fen))
# Check that the half-move part is valid.
try:
halfmove_part = parts.pop(0)
except IndexError:
halfmove_clock = 0
else:
try:
halfmove_clock = int(halfmove_part)
except ValueError:
raise ValueError("invalid half-move clock in fen: {!r}".format(fen))
if halfmove_clock < 0:
raise ValueError("half-move clock cannot be negative: {!r}".format(fen))
# Check that the full-move number part is valid.
# 0 is allowed for compability, but later replaced with 1.
try:
fullmove_part = parts.pop(0)
except IndexError:
fullmove_number = 1
else:
try:
fullmove_number = int(fullmove_part)
except ValueError:
raise ValueError("invalid fullmove number in fen: {!r}".format(fen))
if fullmove_number < 0:
raise ValueError("fullmove number cannot be negative: {!r}".format(fen))
fullmove_number = max(fullmove_number, 1)
# All parts should be consumed now.
if parts:
raise ValueError("fen string has more parts than expected: {!r}".format(fen))
# Validate the board part and set it.
self._set_board_fen(board_part)
# Apply.
self.turn = turn
self._set_castling_fen(castling_part)
self.ep_square = ep_square
self.halfmove_clock = halfmove_clock
self.fullmove_number = fullmove_number
self.clear_stack() | python | def set_fen(self, fen: str) -> None:
"""
Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid.
"""
parts = fen.split()
# Board part.
try:
board_part = parts.pop(0)
except IndexError:
raise ValueError("empty fen")
# Turn.
try:
turn_part = parts.pop(0)
except IndexError:
turn = WHITE
else:
if turn_part == "w":
turn = WHITE
elif turn_part == "b":
turn = BLACK
else:
raise ValueError("expected 'w' or 'b' for turn part of fen: {!r}".format(fen))
# Validate castling part.
try:
castling_part = parts.pop(0)
except IndexError:
castling_part = "-"
else:
if not FEN_CASTLING_REGEX.match(castling_part):
raise ValueError("invalid castling part in fen: {!r}".format(fen))
# En passant square.
try:
ep_part = parts.pop(0)
except IndexError:
ep_square = None
else:
try:
ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part)
except ValueError:
raise ValueError("invalid en passant part in fen: {!r}".format(fen))
# Check that the half-move part is valid.
try:
halfmove_part = parts.pop(0)
except IndexError:
halfmove_clock = 0
else:
try:
halfmove_clock = int(halfmove_part)
except ValueError:
raise ValueError("invalid half-move clock in fen: {!r}".format(fen))
if halfmove_clock < 0:
raise ValueError("half-move clock cannot be negative: {!r}".format(fen))
# Check that the full-move number part is valid.
# 0 is allowed for compability, but later replaced with 1.
try:
fullmove_part = parts.pop(0)
except IndexError:
fullmove_number = 1
else:
try:
fullmove_number = int(fullmove_part)
except ValueError:
raise ValueError("invalid fullmove number in fen: {!r}".format(fen))
if fullmove_number < 0:
raise ValueError("fullmove number cannot be negative: {!r}".format(fen))
fullmove_number = max(fullmove_number, 1)
# All parts should be consumed now.
if parts:
raise ValueError("fen string has more parts than expected: {!r}".format(fen))
# Validate the board part and set it.
self._set_board_fen(board_part)
# Apply.
self.turn = turn
self._set_castling_fen(castling_part)
self.ep_square = ep_square
self.halfmove_clock = halfmove_clock
self.fullmove_number = fullmove_number
self.clear_stack() | [
"def",
"set_fen",
"(",
"self",
",",
"fen",
":",
"str",
")",
"->",
"None",
":",
"parts",
"=",
"fen",
".",
"split",
"(",
")",
"# Board part.",
"try",
":",
"board_part",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"raise",
"V... | Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid. | [
"Parses",
"a",
"FEN",
"and",
"sets",
"the",
"position",
"from",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2157-L2248 |
224,895 | niklasf/python-chess | chess/__init__.py | Board.chess960_pos | def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored.
"""
if self.ep_square:
return None
if not ignore_turn:
if self.turn != WHITE:
return None
if not ignore_castling:
if self.clean_castling_rights() != self.rooks:
return None
if not ignore_counters:
if self.fullmove_number != 1 or self.halfmove_clock != 0:
return None
return super().chess960_pos() | python | def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored.
"""
if self.ep_square:
return None
if not ignore_turn:
if self.turn != WHITE:
return None
if not ignore_castling:
if self.clean_castling_rights() != self.rooks:
return None
if not ignore_counters:
if self.fullmove_number != 1 or self.halfmove_clock != 0:
return None
return super().chess960_pos() | [
"def",
"chess960_pos",
"(",
"self",
",",
"*",
",",
"ignore_turn",
":",
"bool",
"=",
"False",
",",
"ignore_castling",
":",
"bool",
"=",
"False",
",",
"ignore_counters",
":",
"bool",
"=",
"True",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",... | Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored. | [
"Gets",
"the",
"Chess960",
"starting",
"position",
"index",
"between",
"0",
"and",
"956",
"or",
"None",
"if",
"the",
"current",
"position",
"is",
"not",
"a",
"Chess960",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2312-L2337 |
224,896 | niklasf/python-chess | chess/__init__.py | Board.epd | def epd(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str:
"""
Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;'
"""
if en_passant == "fen":
ep_square = self.ep_square
elif en_passant == "xfen":
ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None
else:
ep_square = self.ep_square if self.has_legal_en_passant() else None
epd = [self.board_fen(promoted=promoted),
"w" if self.turn == WHITE else "b",
self.castling_shredder_fen() if shredder else self.castling_xfen(),
SQUARE_NAMES[ep_square] if ep_square is not None else "-"]
if operations:
epd.append(self._epd_operations(operations))
return " ".join(epd) | python | def epd(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str:
"""
Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;'
"""
if en_passant == "fen":
ep_square = self.ep_square
elif en_passant == "xfen":
ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None
else:
ep_square = self.ep_square if self.has_legal_en_passant() else None
epd = [self.board_fen(promoted=promoted),
"w" if self.turn == WHITE else "b",
self.castling_shredder_fen() if shredder else self.castling_xfen(),
SQUARE_NAMES[ep_square] if ep_square is not None else "-"]
if operations:
epd.append(self._epd_operations(operations))
return " ".join(epd) | [
"def",
"epd",
"(",
"self",
",",
"*",
",",
"shredder",
":",
"bool",
"=",
"False",
",",
"en_passant",
":",
"str",
"=",
"\"legal\"",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"*",
"*",
"operations",
":",
"Union",
"[",
"None... | Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;' | [
"Gets",
"an",
"EPD",
"representation",
"of",
"the",
"current",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2398-L2435 |
224,897 | niklasf/python-chess | chess/__init__.py | Board.lan | def lan(self, move: Move) -> str:
"""
Gets the long algebraic notation of the given move in the context of
the current position.
"""
return self._algebraic(move, long=True) | python | def lan(self, move: Move) -> str:
"""
Gets the long algebraic notation of the given move in the context of
the current position.
"""
return self._algebraic(move, long=True) | [
"def",
"lan",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"str",
":",
"return",
"self",
".",
"_algebraic",
"(",
"move",
",",
"long",
"=",
"True",
")"
] | Gets the long algebraic notation of the given move in the context of
the current position. | [
"Gets",
"the",
"long",
"algebraic",
"notation",
"of",
"the",
"given",
"move",
"in",
"the",
"context",
"of",
"the",
"current",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2568-L2573 |
224,898 | niklasf/python-chess | chess/__init__.py | Board.parse_san | def parse_san(self, san: str) -> Move:
"""
Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous.
"""
# Castling.
try:
if san in ["O-O", "O-O+", "O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move))
except StopIteration:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
# Match normal moves.
match = SAN_REGEX.match(san)
if not match:
# Null moves.
if san in ["--", "Z0"]:
return Move.null()
raise ValueError("invalid san: {!r}".format(san))
# Get target square.
to_square = SQUARE_NAMES.index(match.group(4))
to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn]
# Get the promotion type.
p = match.group(5)
promotion = p and PIECE_SYMBOLS.index(p[-1].lower())
# Filter by piece type.
if match.group(1):
piece_type = PIECE_SYMBOLS.index(match.group(1).lower())
from_mask = self.pieces_mask(piece_type, self.turn)
else:
from_mask = self.pawns
# Filter by source file.
if match.group(2):
from_mask &= BB_FILES[FILE_NAMES.index(match.group(2))]
# Filter by source rank.
if match.group(3):
from_mask &= BB_RANKS[int(match.group(3)) - 1]
# Match legal moves.
matched_move = None
for move in self.generate_legal_moves(from_mask, to_mask):
if move.promotion != promotion:
continue
if matched_move:
raise ValueError("ambiguous san: {!r} in {}".format(san, self.fen()))
matched_move = move
if not matched_move:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
return matched_move | python | def parse_san(self, san: str) -> Move:
"""
Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous.
"""
# Castling.
try:
if san in ["O-O", "O-O+", "O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move))
except StopIteration:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
# Match normal moves.
match = SAN_REGEX.match(san)
if not match:
# Null moves.
if san in ["--", "Z0"]:
return Move.null()
raise ValueError("invalid san: {!r}".format(san))
# Get target square.
to_square = SQUARE_NAMES.index(match.group(4))
to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn]
# Get the promotion type.
p = match.group(5)
promotion = p and PIECE_SYMBOLS.index(p[-1].lower())
# Filter by piece type.
if match.group(1):
piece_type = PIECE_SYMBOLS.index(match.group(1).lower())
from_mask = self.pieces_mask(piece_type, self.turn)
else:
from_mask = self.pawns
# Filter by source file.
if match.group(2):
from_mask &= BB_FILES[FILE_NAMES.index(match.group(2))]
# Filter by source rank.
if match.group(3):
from_mask &= BB_RANKS[int(match.group(3)) - 1]
# Match legal moves.
matched_move = None
for move in self.generate_legal_moves(from_mask, to_mask):
if move.promotion != promotion:
continue
if matched_move:
raise ValueError("ambiguous san: {!r} in {}".format(san, self.fen()))
matched_move = move
if not matched_move:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
return matched_move | [
"def",
"parse_san",
"(",
"self",
",",
"san",
":",
"str",
")",
"->",
"Move",
":",
"# Castling.",
"try",
":",
"if",
"san",
"in",
"[",
"\"O-O\"",
",",
"\"O-O+\"",
",",
"\"O-O#\"",
"]",
":",
"return",
"next",
"(",
"move",
"for",
"move",
"in",
"self",
"... | Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous. | [
"Uses",
"the",
"current",
"position",
"as",
"the",
"context",
"to",
"parse",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"and",
"returns",
"the",
"corresponding",
"move",
"object",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2698-L2762 |
224,899 | niklasf/python-chess | chess/__init__.py | Board.push_san | def push_san(self, san: str) -> Move:
"""
Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move.
"""
move = self.parse_san(san)
self.push(move)
return move | python | def push_san(self, san: str) -> Move:
"""
Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move.
"""
move = self.parse_san(san)
self.push(move)
return move | [
"def",
"push_san",
"(",
"self",
",",
"san",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"parse_san",
"(",
"san",
")",
"self",
".",
"push",
"(",
"move",
")",
"return",
"move"
] | Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move. | [
"Parses",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"makes",
"the",
"move",
"and",
"puts",
"it",
"on",
"the",
"the",
"move",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2764-L2775 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.