Remove any syntax required for python < 3.8

find . -iname "*.py" -exec pyupgrade --py38-plus {} \;
pull/376/head
Hugo Osvaldo Barrera 2022-08-15 09:55:50 +02:00
rodzic f2717a4b85
commit d4c190866f
25 zmienionych plików z 72 dodań i 115 usunięć

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# icalendar documentation build configuration file
import pkg_resources
import datetime
@ -26,9 +25,9 @@ extensions = [
source_suffix = '.rst'
master_doc = 'index'
project = u'icalendar'
project = 'icalendar'
this_year = datetime.date.today().year
copyright = u'{}, Plone Foundation'.format(this_year)
copyright = f'{this_year}, Plone Foundation'
version = pkg_resources.get_distribution('icalendar').version
release = version
@ -38,6 +37,6 @@ pygments_style = 'sphinx'
htmlhelp_basename = 'icalendardoc'
man_pages = [
('index', 'icalendar', u'icalendar Documentation',
[u'Plone Foundation'], 1)
('index', 'icalendar', 'icalendar Documentation',
['Plone Foundation'], 1)
]

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import codecs
import setuptools
import re

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
__version__ = '5.0.0a2.dev0'
from icalendar.cal import (

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Calendar is a dictionary like Python object that can render itself as VCAL
files according to rfc2445.
@ -34,7 +33,7 @@ class ComponentFactory(CaselessDict):
def __init__(self, *args, **kwargs):
"""Set keys to upper for initial dict.
"""
super(ComponentFactory, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self['VEVENT'] = Event
self['VTODO'] = Todo
self['VJOURNAL'] = Journal
@ -79,7 +78,7 @@ class Component(CaselessDict):
def __init__(self, *args, **kwargs):
"""Set keys to upper for initial dict.
"""
super(Component, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# set parameters here for properties that use non-default values
self.subcomponents = [] # Components can be nested.
self.errors = [] # If we ignored exception(s) while
@ -393,12 +392,12 @@ class Component(CaselessDict):
if multiple:
return comps
if len(comps) > 1:
raise ValueError('Found multiple components where '
'only one is allowed: {st!r}'.format(**locals()))
raise ValueError(f'Found multiple components where '
f'only one is allowed: {st!r}')
if len(comps) < 1:
raise ValueError('Found no components where '
'exactly one is required: '
'{st!r}'.format(**locals()))
raise ValueError(f'Found no components where '
f'exactly one is required: '
f'{st!r}')
return comps[0]
def content_line(self, name, value, sorted=True):
@ -430,7 +429,7 @@ class Component(CaselessDict):
"""String representation of class with all of it's subcomponents.
"""
subs = ', '.join([str(it) for it in self.subcomponents])
return '%s(%s%s)' % (
return '{}({}{})'.format(
self.name or type(self).__name__,
dict(self),
', %s' % subs if subs else ''
@ -607,7 +606,7 @@ class Timezone(Component):
tzname = component['TZNAME'].encode('ascii', 'replace')
tzname = self._make_unique_tzname(tzname, tznames)
except KeyError:
tzname = '{0}_{1}_{2}_{3}'.format(
tzname = '{}_{}_{}_{}'.format(
zone,
component['DTSTART'].to_ical().decode('utf-8'),
component['TZOFFSETFROM'].to_ical(), # for whatever reason this is str/unicode

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from icalendar.compat import iteritems
from icalendar.parser_tools import to_unicode
@ -30,47 +29,47 @@ class CaselessDict(OrderedDict):
def __init__(self, *args, **kwargs):
"""Set keys to upper for initial dict.
"""
super(CaselessDict, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
for key, value in self.items():
key_upper = to_unicode(key).upper()
if key != key_upper:
super(CaselessDict, self).__delitem__(key)
super().__delitem__(key)
self[key_upper] = value
def __getitem__(self, key):
key = to_unicode(key)
return super(CaselessDict, self).__getitem__(key.upper())
return super().__getitem__(key.upper())
def __setitem__(self, key, value):
key = to_unicode(key)
super(CaselessDict, self).__setitem__(key.upper(), value)
super().__setitem__(key.upper(), value)
def __delitem__(self, key):
key = to_unicode(key)
super(CaselessDict, self).__delitem__(key.upper())
super().__delitem__(key.upper())
def __contains__(self, key):
key = to_unicode(key)
return super(CaselessDict, self).__contains__(key.upper())
return super().__contains__(key.upper())
def get(self, key, default=None):
key = to_unicode(key)
return super(CaselessDict, self).get(key.upper(), default)
return super().get(key.upper(), default)
def setdefault(self, key, value=None):
key = to_unicode(key)
return super(CaselessDict, self).setdefault(key.upper(), value)
return super().setdefault(key.upper(), value)
def pop(self, key, default=None):
key = to_unicode(key)
return super(CaselessDict, self).pop(key.upper(), default)
return super().pop(key.upper(), default)
def popitem(self):
return super(CaselessDict, self).popitem()
return super().popitem()
def has_key(self, key):
key = to_unicode(key)
return super(CaselessDict, self).__contains__(key.upper())
return super().__contains__(key.upper())
def update(self, *args, **kwargs):
# Multiple keys where key1.upper() == key2.upper() will be lost.
@ -82,10 +81,10 @@ class CaselessDict(OrderedDict):
self[key] = value
def copy(self):
return type(self)(super(CaselessDict, self).copy())
return type(self)(super().copy())
def __repr__(self):
return '%s(%s)' % (type(self).__name__, dict(self))
return f'{type(self).__name__}({dict(self)})'
def __eq__(self, other):
return self is other or dict(self.items()) == dict(other.items())

Wyświetl plik

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
"""iCalendar utility"""
from __future__ import unicode_literals
import argparse
import sys
@ -81,7 +79,7 @@ def main():
description=__doc__)
parser.add_argument(
'-v', '--version', action='version',
version='{} version {}'.format(parser.prog, __version__))
version=f'{parser.prog} version {__version__}')
# This seems a bit of an overkill now, but we will probably add more
# functionality later, e.g., iCalendar to JSON / YAML and vice versa.

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import sys

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""This module parses and generates contentlines as defined in RFC 2445
(iCalendar), but will probably work for other MIME types with similar syntax.
Eg. RFC 2426 (vCard)
@ -6,7 +5,6 @@ Eg. RFC 2426 (vCard)
It is stupid in the sense that it treats the content purely as strings. No type
conversion is attempted.
"""
from __future__ import unicode_literals
from icalendar import compat
from icalendar.caselessdict import CaselessDict
@ -293,7 +291,7 @@ class Contentline(compat.unicode_type):
value = to_unicode(value, encoding=encoding)
assert '\n' not in value, ('Content line can not contain unescaped '
'new line characters.')
self = super(Contentline, cls).__new__(cls, value)
self = super().__new__(cls, value)
self.strict = strict
return self
@ -315,8 +313,8 @@ class Contentline(compat.unicode_type):
values = to_unicode(values)
if params:
params = to_unicode(params.to_ical(sorted=sorted))
return cls('%s;%s:%s' % (name, params, values))
return cls('%s:%s' % (name, values))
return cls(f'{name};{params}:{values}')
return cls(f'{name}:{values}')
def parts(self):
"""Split the content line up into (name, parameters, values) parts.

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from icalendar import compat

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""This module contains the parser/generators (or coders/encoders if you
prefer) for the classes/datatypes that are used in iCalendar:
@ -67,7 +66,7 @@ import time as _time
DATE_PART = r'(\d+)D'
TIME_PART = r'T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?'
DATETIME_PART = '(?:%s)?(?:%s)?' % (DATE_PART, TIME_PART)
DATETIME_PART = f'(?:{DATE_PART})?(?:{TIME_PART})?'
WEEKS_PART = r'(\d+)W'
DURATION_REGEX = re.compile(r'([-+]?)P(?:%s|%s)$'
% (WEEKS_PART, DATETIME_PART))
@ -133,7 +132,7 @@ class LocalTimezone(tzinfo):
return tt.tm_isdst > 0
class vBinary(object):
class vBinary:
"""Binary property values are base 64 encoded.
"""
@ -161,7 +160,7 @@ class vBoolean(int):
BOOL_MAP = CaselessDict({'true': True, 'false': False})
def __new__(cls, *args, **kwargs):
self = super(vBoolean, cls).__new__(cls, *args, **kwargs)
self = super().__new__(cls, *args, **kwargs)
self.params = Parameters()
return self
@ -183,7 +182,7 @@ class vCalAddress(compat.unicode_type):
"""
def __new__(cls, value, encoding=DEFAULT_ENCODING):
value = to_unicode(value, encoding=encoding)
self = super(vCalAddress, cls).__new__(cls, value)
self = super().__new__(cls, value)
self.params = Parameters()
return self
@ -202,7 +201,7 @@ class vFloat(float):
"""Just a float.
"""
def __new__(cls, *args, **kwargs):
self = super(vFloat, cls).__new__(cls, *args, **kwargs)
self = super().__new__(cls, *args, **kwargs)
self.params = Parameters()
return self
@ -221,7 +220,7 @@ class vInt(int):
"""Just an int.
"""
def __new__(cls, *args, **kwargs):
self = super(vInt, cls).__new__(cls, *args, **kwargs)
self = super().__new__(cls, *args, **kwargs)
self.params = Parameters()
return self
@ -236,7 +235,7 @@ class vInt(int):
raise ValueError('Expected int, got: %s' % ical)
class vDDDLists(object):
class vDDDLists:
"""A list of vDDDTypes values.
"""
def __init__(self, dt_list):
@ -267,7 +266,7 @@ class vDDDLists(object):
out.append(vDDDTypes.from_ical(ical_dt, timezone=timezone))
return out
class vCategory(object):
class vCategory:
def __init__(self, c_list):
if not hasattr(c_list, '__iter__'):
@ -284,7 +283,7 @@ class vCategory(object):
return out
class vDDDTypes(object):
class vDDDTypes:
"""A combined Datetime, Date or Duration parser/generator. Their format
cannot be confused, and often values can be of either types.
So this is practical.
@ -326,7 +325,7 @@ class vDDDTypes(object):
elif isinstance(dt, tuple) and len(dt) == 2:
return vPeriod(dt).to_ical()
else:
raise ValueError('Unknown date type: {}'.format(type(dt)))
raise ValueError(f'Unknown date type: {type(dt)}')
@classmethod
def from_ical(cls, ical, timezone=None):
@ -350,7 +349,7 @@ class vDDDTypes(object):
)
class vDate(object):
class vDate:
"""Render and generates iCalendar date format.
"""
def __init__(self, dt):
@ -376,7 +375,7 @@ class vDate(object):
raise ValueError('Wrong date format %s' % ical)
class vDatetime(object):
class vDatetime:
"""Render and generates icalendar datetime format.
vDatetime is timezone aware and uses the pytz library, an implementation of
@ -442,7 +441,7 @@ class vDatetime(object):
raise ValueError('Wrong datetime format: %s' % ical)
class vDuration(object):
class vDuration:
"""Subclass of timedelta that renders itself in the iCalendar DURATION
format.
"""
@ -498,7 +497,7 @@ class vDuration(object):
raise ValueError('Invalid iCalendar duration: %s' % ical)
class vPeriod(object):
class vPeriod:
"""A precise period of time.
"""
def __init__(self, per):
@ -567,7 +566,7 @@ class vPeriod(object):
p = (self.start, self.duration)
else:
p = (self.start, self.end)
return 'vPeriod(%r)' % (p, )
return f'vPeriod({p!r})'
class vWeekday(compat.unicode_type):
@ -579,7 +578,7 @@ class vWeekday(compat.unicode_type):
def __new__(cls, value, encoding=DEFAULT_ENCODING):
value = to_unicode(value, encoding=encoding)
self = super(vWeekday, cls).__new__(cls, value)
self = super().__new__(cls, value)
match = WEEKDAY_RULE.match(self)
if match is None:
raise ValueError('Expected weekday abbrevation, got: %s' % self)
@ -620,7 +619,7 @@ class vFrequency(compat.unicode_type):
def __new__(cls, value, encoding=DEFAULT_ENCODING):
value = to_unicode(value, encoding=encoding)
self = super(vFrequency, cls).__new__(cls, value)
self = super().__new__(cls, value)
if self not in vFrequency.frequencies:
raise ValueError('Expected frequency, got: %s' % self)
self.params = Parameters()
@ -669,7 +668,7 @@ class vRecur(CaselessDict):
})
def __init__(self, *args, **kwargs):
super(vRecur, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.params = Parameters()
def to_ical(self):
@ -717,7 +716,7 @@ class vText(compat.unicode_type):
def __new__(cls, value, encoding=DEFAULT_ENCODING):
value = to_unicode(value, encoding=encoding)
self = super(vText, cls).__new__(cls, value)
self = super().__new__(cls, value)
self.encoding = encoding
self.params = Parameters()
return self
@ -734,7 +733,7 @@ class vText(compat.unicode_type):
return cls(ical_unesc)
class vTime(object):
class vTime:
"""Render and generates iCalendar time format.
"""
@ -766,7 +765,7 @@ class vUri(compat.unicode_type):
def __new__(cls, value, encoding=DEFAULT_ENCODING):
value = to_unicode(value, encoding=encoding)
self = super(vUri, cls).__new__(cls, value)
self = super().__new__(cls, value)
self.params = Parameters()
return self
@ -781,7 +780,7 @@ class vUri(compat.unicode_type):
raise ValueError('Expected , got: %s' % ical)
class vGeo(object):
class vGeo:
"""A special type that is only indirectly defined in the rfc.
"""
@ -798,7 +797,7 @@ class vGeo(object):
self.params = Parameters()
def to_ical(self):
return '%s;%s' % (self.latitude, self.longitude)
return f'{self.latitude};{self.longitude}'
@staticmethod
def from_ical(ical):
@ -809,7 +808,7 @@ class vGeo(object):
raise ValueError("Expected 'float;float' , got: %s" % ical)
class vUTCOffset(object):
class vUTCOffset:
"""Renders itself as a utc offset.
"""
@ -872,7 +871,7 @@ class vInline(compat.unicode_type):
"""
def __new__(cls, value, encoding=DEFAULT_ENCODING):
value = to_unicode(value, encoding=encoding)
self = super(vInline, cls).__new__(cls, value)
self = super().__new__(cls, value)
self.params = Parameters()
return self
@ -894,7 +893,7 @@ class TypesFactory(CaselessDict):
def __init__(self, *args, **kwargs):
"Set keys to upper for initial dict"
super(TypesFactory, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.all_types = (
vBinary,
vBoolean,

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import datetime

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from icalendar.parser_tools import to_unicode
import unittest
@ -471,8 +468,8 @@ END:VCALENDAR"""
self.assertEqual(dtstart, expected)
try:
expected_zone = str('(UTC-03:00) Brasília')
expected_tzname = str('Brasília standard')
expected_zone = '(UTC-03:00) Brasília'
expected_tzname = 'Brasília standard'
except UnicodeEncodeError:
expected_zone = '(UTC-03:00) Brasília'.encode('ascii', 'replace')
expected_tzname = 'Brasília standard'.encode('ascii', 'replace')

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import icalendar
import os
import textwrap
@ -165,14 +162,14 @@ class IcalendarTestCase (unittest.TestCase):
)
# And the traditional failure
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
ValueError,
'Content line could not be parsed into parts'
):
Contentline('ATTENDEE;maxm@example.com').parts()
# Another failure:
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
ValueError,
'Content line could not be parsed into parts'
):
@ -189,7 +186,7 @@ class IcalendarTestCase (unittest.TestCase):
)
# Should bomb on missing param:
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
ValueError,
'Content line could not be parsed into parts'
):
@ -214,12 +211,12 @@ class IcalendarTestCase (unittest.TestCase):
)
contains_base64 = (
'X-APPLE-STRUCTURED-LOCATION;'
'VALUE=URI;X-ADDRESS="Kaiserliche Hofburg, 1010 Wien";'
'X-APPLE-MAPKIT-HANDLE=CAESxQEZgr3QZXJyZWljaA==;'
'X-APPLE-RADIUS=328.7978217977285;X-APPLE-REFERENCEFRAME=1;'
'X-TITLE=Heldenplatz:geo:48.206686,16.363235'
).encode('utf-8')
b'X-APPLE-STRUCTURED-LOCATION;'
b'VALUE=URI;X-ADDRESS="Kaiserliche Hofburg, 1010 Wien";'
b'X-APPLE-MAPKIT-HANDLE=CAESxQEZgr3QZXJyZWljaA==;'
b'X-APPLE-RADIUS=328.7978217977285;X-APPLE-REFERENCEFRAME=1;'
b'X-TITLE=Heldenplatz:geo:48.206686,16.363235'
)
self.assertEqual(
Contentline(contains_base64, strict=True).parts(),
@ -252,7 +249,7 @@ class IcalendarTestCase (unittest.TestCase):
# at least just but bytes in there
# porting it to "run" under python 2 & 3 makes it not much better
with self.assertRaises(AssertionError):
foldline('привет'.encode('utf-8'), limit=3)
foldline('привет'.encode(), limit=3)
self.assertEqual(foldline('foobar', limit=4), 'foo\r\n bar')
self.assertEqual(

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from icalendar import Calendar
from icalendar.prop import vText
import unittest

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from icalendar import Calendar
from icalendar import Event
from icalendar import Parameters

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from icalendar.caselessdict import CaselessDict
import unittest

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import unittest
import datetime

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import datetime

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from datetime import timedelta
import unittest

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import unittest
import icalendar

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from icalendar.parser_tools import data_encode
from icalendar.parser_tools import to_unicode
import unittest
@ -12,9 +9,9 @@ class TestParserTools(unittest.TestCase):
self.assertEqual(to_unicode(b'spam'), 'spam')
self.assertEqual(to_unicode('spam'), 'spam')
self.assertEqual(to_unicode('spam'.encode('utf-8')), 'spam')
self.assertEqual(to_unicode(b'spam'), 'spam')
self.assertEqual(to_unicode(b'\xc6\xb5'), '\u01b5')
self.assertEqual(to_unicode('\xc6\xb5'.encode('iso-8859-1')),
self.assertEqual(to_unicode(b'\xc6\xb5'),
'\u01b5')
self.assertEqual(to_unicode(b'\xc6\xb5', encoding='ascii'), '\u01b5')
self.assertEqual(to_unicode(1), 1)

Wyświetl plik

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import date
from datetime import datetime
from datetime import time

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import unittest
from icalendar.tools import UIDGenerator

Wyświetl plik

@ -1,3 +1,2 @@
# -*- coding: utf-8 -*-
# we save all timezone with TZIDs unknow to the TZDB in here
_timezone_cache = {}

Wyświetl plik

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from datetime import datetime
from icalendar.parser_tools import to_unicode
from icalendar.prop import vDatetime
@ -9,7 +8,7 @@ from string import digits
import random
class UIDGenerator(object):
class UIDGenerator:
"""If you are too lazy to create real uid's.
"""
@ -31,6 +30,6 @@ class UIDGenerator(object):
host_name = to_unicode(host_name)
unique = unique or UIDGenerator.rnd_string()
today = to_unicode(vDatetime(datetime.today()).to_ical())
return vText('%s-%s@%s' % (today,
return vText('{}-{}@{}'.format(today,
unique,
host_name))