Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
79a76f6
adding mypy to the repo
Poolitzer Feb 20, 2020
22a45a0
first take on only testing changed files
Poolitzer Feb 20, 2020
f61fecf
allowing test branch
Poolitzer Feb 20, 2020
1e94485
improving start condition of workflow
Poolitzer Feb 20, 2020
6a51275
Add mypy to pre-commit and make
Bibo-Joshi Mar 7, 2020
a89828a
Try computing typing coverage in CI
Bibo-Joshi Mar 7, 2020
656c2bd
Save coverage report as artifact
Bibo-Joshi Mar 8, 2020
e5f5867
Drop py3.5, use mypy options instead of diff-cover
Bibo-Joshi Apr 25, 2020
c856bbb
use spaces over tabs in makefile
Bibo-Joshi Apr 25, 2020
783e5d4
Remove deprecated getargspec
Bibo-Joshi May 12, 2020
e13bb33
Refactor de_json
Bibo-Joshi May 12, 2020
9160674
Annotate all the things! (Except tg.ext)
Bibo-Joshi May 15, 2020
d84444b
Merge branch 'master' into type_hinting_master
Bibo-Joshi May 15, 2020
7f4410d
Annotate InputMedia, Custom Aliases, improve file typing
Bibo-Joshi May 15, 2020
f87fa10
Move de_list to TelegramObject
Bibo-Joshi May 15, 2020
4b9c010
Persistence & Handlers
Bibo-Joshi May 16, 2020
1a22799
Filters
Bibo-Joshi May 16, 2020
9a545be
JobQueue & Job
Bibo-Joshi May 16, 2020
be15033
Dispatcher
Bibo-Joshi May 16, 2020
db78e06
MessageQueue
Bibo-Joshi May 16, 2020
b74d0db
Some fixes
Bibo-Joshi May 16, 2020
f0c972e
Merge branch 'master' into type_hinting_master
Bibo-Joshi Jun 15, 2020
84e49a6
utils.typing -> utils.types + 2 newlines
Bibo-Joshi Jun 16, 2020
a8895a2
Merge branch 'v13' into type_hinting_master
Bibo-Joshi Jul 12, 2020
773430d
Temporarily enable tests for the v13 branch
Bibo-Joshi Jun 6, 2020
6fd3d2f
Refactor handling of kwargs in Bot methods (#1924)
Bibo-Joshi Jun 30, 2020
9c38dae
Refactor JobQueue (#1981)
Bibo-Joshi Jul 10, 2020
3418ba2
Refactor persistence of Bot instances (#1994)
Bibo-Joshi Jul 13, 2020
1e29c1a
Extend rich comparison of objects (#1724)
Bibo-Joshi Jul 14, 2020
eb8d65b
Merge branch 'v13' into type_hinting_master
Bibo-Joshi Jul 16, 2020
dee672d
Temporarily enable tests for the v13 branch
Bibo-Joshi Jun 6, 2020
02b058c
Refactor handling of kwargs in Bot methods (#1924)
Bibo-Joshi Jun 30, 2020
958a41e
Refactor JobQueue (#1981)
Bibo-Joshi Jul 10, 2020
c3a426a
Refactor persistence of Bot instances (#1994)
Bibo-Joshi Jul 13, 2020
fe9370a
Extend rich comparison of objects (#1724)
Bibo-Joshi Jul 14, 2020
f74be43
Refactor handling of default_quote (#1965)
Bibo-Joshi Jul 19, 2020
87a426e
Refactor Handling of Message VS Update Filters (#2032)
Bibo-Joshi Jul 28, 2020
ad30a8f
Make context-based callbacks the default setting (#2050)
Bibo-Joshi Aug 16, 2020
2a67404
Merge branch 'v13' into type_hinting_master
Bibo-Joshi Aug 16, 2020
9fb50f3
Temporarily enable tests for the v13 branch
Bibo-Joshi Jun 6, 2020
274f6b4
Refactor handling of kwargs in Bot methods (#1924)
Bibo-Joshi Jun 30, 2020
295805b
Refactor JobQueue (#1981)
Bibo-Joshi Jul 10, 2020
75ca2ba
Refactor persistence of Bot instances (#1994)
Bibo-Joshi Jul 13, 2020
47bde49
Extend rich comparison of objects (#1724)
Bibo-Joshi Jul 14, 2020
c7c9790
Refactor handling of default_quote (#1965)
Bibo-Joshi Jul 19, 2020
da98330
Refactor Handling of Message VS Update Filters (#2032)
Bibo-Joshi Jul 28, 2020
85c6831
Make context-based callbacks the default setting (#2050)
Bibo-Joshi Aug 16, 2020
b090050
Merge branch 'v13' into type_hinting_master
Bibo-Joshi Sep 13, 2020
f39dbd6
Merge branch 'v13' into type_hinting_master
Bibo-Joshi Sep 27, 2020
b72ac15
address review
Bibo-Joshi Oct 4, 2020
0ad6649
Merge branch 'v13' into type_hinting_master
Bibo-Joshi Oct 4, 2020
96b929f
Use NoReturn where possible
Bibo-Joshi Oct 4, 2020
4398205
Try ignoring the if TYPE_CHECKING lines in coverage report
Bibo-Joshi Oct 6, 2020
6edc522
minor fix
Bibo-Joshi Oct 6, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ Here's how to make a one-off code change.
- You can refer to relevant issues in the commit message by writing, e.g., "#105".

- Your code should adhere to the `PEP 8 Style Guide`_, with the exception that we have a maximum line length of 99.


- Provide static typing with signature annotations. The documentation of `MyPy`_ will be a good start, the cheat sheet is `here`_. We also have some custom type aliases in ``telegram.utils.helpers.typing``.

- Document your code. This project uses `sphinx`_ to generate static HTML docs. To build them, first make sure you have the required dependencies:

.. code-block:: bash
Expand Down Expand Up @@ -251,3 +253,5 @@ break the API classes. For example:
.. _`Google Python Style Guide`: http://google.github.io/styleguide/pyguide.html
.. _`Google Python Style Docstrings`: https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
.. _AUTHORS.rst: ../AUTHORS.rst
.. _`MyPy`: https://mypy.readthedocs.io/en/stable/index.html
.. _`here`: https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ htmlcov/
.coverage.*
.cache
.pytest_cache
.mypy_cache
nosetests.xml
coverage.xml
*,cover
Expand Down
7 changes: 6 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ repos:
args:
- --diff
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.1
rev: 3.8.1
hooks:
- id: flake8
- repo: git://github.com/pre-commit/mirrors-pylint
Expand All @@ -18,3 +18,8 @@ repos:
args:
- --errors-only
- --disable=import-error
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v0.770'
hooks:
- id: mypy
files: ^telegram/.*\.py$
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ PYTEST := pytest
PEP257 := pep257
PEP8 := flake8
YAPF := yapf
MYPY := mypy
PIP := pip

clean:
Expand All @@ -28,6 +29,9 @@ yapf:
lint:
$(PYLINT) -E telegram --disable=no-name-in-module,import-error

mypy:
$(MYPY) -p telegram

test:
$(PYTEST) -v

Expand All @@ -41,6 +45,7 @@ help:
@echo "- pep8 Check style with flake8"
@echo "- lint Check style with pylint"
@echo "- yapf Check style with yapf"
@echo "- mypy Check type hinting with mypy"
@echo "- test Run tests using pytest"
@echo
@echo "Available variables:"
Expand All @@ -49,4 +54,5 @@ help:
@echo "- PEP257 default: $(PEP257)"
@echo "- PEP8 default: $(PEP8)"
@echo "- YAPF default: $(YAPF)"
@echo "- MYPY default: $(MYPY)"
@echo "- PIP default: $(PIP)"
1 change: 1 addition & 0 deletions docs/source/telegram.utils.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ telegram.utils package
telegram.utils.helpers
telegram.utils.promise
telegram.utils.request
telegram.utils.types
6 changes: 6 additions & 0 deletions docs/source/telegram.utils.types.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
telegram.utils.types Module
===========================

.. automodule:: telegram.utils.types
:members:
:show-inheritance:
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pep257
pylint
flaky
yapf
mypy==0.770
pre-commit
beautifulsoup4
pytest==4.2.0
Expand Down
19 changes: 19 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,22 @@ omit =
telegram/__main__.py
telegram/vendor/*

[coverage:report]
exclude_lines =
if TYPE_CHECKING:

[mypy]
warn_unused_ignores = True
warn_unused_configs = True
disallow_untyped_defs = True
disallow_incomplete_defs = True
disallow_untyped_decorators = True
show_error_codes = True

[mypy-telegram.vendor.*]
ignore_errors = True

# Disable strict optional for telegram objects with class methods
# We don't want to clutter the code with 'if self.bot is None: raise RuntimeError()'
[mypy-telegram.callbackquery,telegram.chat,telegram.message,telegram.user,telegram.files.*,telegram.inline.inlinequery,telegram.payment.precheckoutquery,telegram.payment.shippingquery,telegram.passport.passportdata,telegram.passport.credentials,telegram.passport.passportfile,telegram.ext.filters]
strict_optional = False
2 changes: 1 addition & 1 deletion telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@
from .update import Update
from .files.inputmedia import (InputMedia, InputMediaVideo, InputMediaPhoto, InputMediaAnimation,
InputMediaAudio, InputMediaDocument)
from .bot import Bot
from .constants import (MAX_MESSAGE_LENGTH, MAX_CAPTION_LENGTH, SUPPORTED_WEBHOOK_PORTS,
MAX_FILESIZE_DOWNLOAD, MAX_FILESIZE_UPLOAD,
MAX_MESSAGES_PER_SECOND_PER_CHAT, MAX_MESSAGES_PER_SECOND,
Expand All @@ -124,6 +123,7 @@
SecureData,
FileCredentials,
TelegramDecryptionError)
from .bot import Bot
from .version import __version__ # noqa: F401

__author__ = 'devs@python-telegram-bot.org'
Expand Down
9 changes: 5 additions & 4 deletions telegram/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@

import certifi

from typing import Optional

from . import __version__ as telegram_ver


def _git_revision():
def _git_revision() -> Optional[str]:
try:
output = subprocess.check_output(["git", "describe", "--long", "--tags"],
stderr=subprocess.STDOUT)
Expand All @@ -34,15 +35,15 @@ def _git_revision():
return output.decode().strip()


def print_ver_info():
def print_ver_info() -> None:
git_revision = _git_revision()
print('python-telegram-bot {}'.format(telegram_ver) + (' ({})'.format(git_revision)
if git_revision else ''))
print('certifi {}'.format(certifi.__version__))
print('certifi {}'.format(certifi.__version__)) # type: ignore[attr-defined]
print('Python {}'.format(sys.version.replace('\n', ' ')))


def main():
def main() -> None:
print_ver_info()


Expand Down
52 changes: 40 additions & 12 deletions telegram/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,36 +17,64 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram Objects."""

try:
import ujson as json
except ImportError:
import json
import json # type: ignore[no-redef]

import warnings

from telegram.utils.types import JSONDict
from typing import Tuple, Any, Optional, Type, TypeVar, TYPE_CHECKING, List

if TYPE_CHECKING:
from telegram import Bot

TO = TypeVar('TO', bound='TelegramObject', covariant=True)


class TelegramObject:
"""Base class for most telegram objects."""

_id_attrs = ()
# def __init__(self, *args: Any, **kwargs: Any):
# pass

def __str__(self):
_id_attrs: Tuple[Any, ...] = ()

def __str__(self) -> str:
return str(self.to_dict())

def __getitem__(self, item):
def __getitem__(self, item: str) -> Any:
return self.__dict__[item]

@staticmethod
def parse_data(data: Optional[JSONDict]) -> Optional[JSONDict]:
if not data:
return None
return data.copy()

@classmethod
def de_json(cls, data, bot):
def de_json(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot') -> Optional[TO]:
data = cls.parse_data(data)

if not data:
return None

data = data.copy()
if cls == TelegramObject:
return cls()
else:
return cls(bot=bot, **data) # type: ignore[call-arg]

return data
@classmethod
def de_list(cls: Type[TO],
data: Optional[List[JSONDict]],
bot: 'Bot') -> List[Optional[TO]]:
if not data:
return []

return [cls.de_json(d, bot) for d in data]

def to_json(self):
def to_json(self) -> str:
"""
Returns:
:obj:`str`
Expand All @@ -55,7 +83,7 @@ def to_json(self):

return json.dumps(self.to_dict())

def to_dict(self):
def to_dict(self) -> JSONDict:
data = dict()

for key in iter(self.__dict__):
Expand All @@ -73,7 +101,7 @@ def to_dict(self):
data['from'] = data.pop('from_user', None)
return data

def __eq__(self, other):
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
if self._id_attrs == ():
warnings.warn("Objects of type {} can not be meaningfully tested for "
Expand All @@ -84,7 +112,7 @@ def __eq__(self, other):
return self._id_attrs == other._id_attrs
return super().__eq__(other) # pylint: disable=no-member

def __hash__(self):
def __hash__(self) -> int:
if self._id_attrs:
return hash((self.__class__, self._id_attrs)) # pylint: disable=no-member
return super().__hash__()
Loading