Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use f-strings #855

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion examples/attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def __init__(self, name):
self.name = name

def __str__(self):
return "<Color: {}>".format(self.name)
return f"<Color: {self.name}>"


class PickleAttribute(BinaryAttribute):
Expand Down
4 changes: 2 additions & 2 deletions examples/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class Meta:

# Indexes can be queried easily using the index's hash key
for item in TestModel.view_index.query(1):
print("Item queried from index: {0}".format(item))
print(f"Item queried from index: {item}")


class GamePlayerOpponentIndex(LocalSecondaryIndex):
Expand Down Expand Up @@ -96,7 +96,7 @@ class Meta:

# Indexes can be queried easily using the index's hash key
for item in GameModel.player_opponent_index.query('1234'):
print("Item queried from index: {0}".format(item))
print(f"Item queried from index: {item}")

# Count on an index
print(GameModel.player_opponent_index.count('1234'))
26 changes: 13 additions & 13 deletions examples/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class Meta:
with Thread.batch_write() as batch:
threads = []
for x in range(100):
thread = Thread('forum-{0}'.format(x), 'subject-{0}'.format(x))
thread = Thread(f'forum-{x}', f'subject-{x}')
thread.tags = ['tag1', 'tag2']
thread.last_post_datetime = datetime.now()
threads.append(thread)
Expand All @@ -74,7 +74,7 @@ class Meta:
print(Thread.count('forum-1'))

# Batch get
item_keys = [('forum-{0}'.format(x), 'subject-{0}'.format(x)) for x in range(100)]
item_keys = [(f'forum-{x}', f'subject-{x}') for x in range(100)]
for item in Thread.batch_get(item_keys):
print(item)

Expand Down Expand Up @@ -121,7 +121,7 @@ class Meta:
with AliasedModel.batch_write() as batch:
threads = []
for x in range(100):
thread = AliasedModel('forum-{0}'.format(x), 'subject-{0}'.format(x))
thread = AliasedModel(f'forum-{x}', f'subject-{x}')
thread.tags = ['tag1', 'tag2']
thread.last_post_datetime = datetime.now()
threads.append(thread)
Expand All @@ -130,30 +130,30 @@ class Meta:
batch.save(thread)

# Batch get
item_keys = [('forum-{0}'.format(x), 'subject-{0}'.format(x)) for x in range(100)]
item_keys = [(f'forum-{x}', f'subject-{x}') for x in range(100)]
for item in AliasedModel.batch_get(item_keys):
print("Batch get item: {0}".format(item))
print(f"Batch get item: {item}")

# Scan
for item in AliasedModel.scan():
print("Scanned item: {0}".format(item))
print(f"Scanned item: {item}")

# Query
for item in AliasedModel.query('forum-1', AliasedModel.subject.startswith('subject')):
print("Query using aliased attribute: {0}".format(item))
print(f"Query using aliased attribute: {item}")

# Query with filters
for item in Thread.query('forum-1', (Thread.views == 0) | (Thread.replies == 0)):
print("Query result: {0}".format(item))
print(f"Query result: {item}")


# Scan with filters
for item in Thread.scan(Thread.subject.startswith('subject') & (Thread.views == 0)):
print("Scanned item: {0} {1}".format(item.subject, item.views))
print(f"Scanned item: {item.subject} {item.views}")

# Scan with null filter
for item in Thread.scan(Thread.subject.startswith('subject') & Thread.last_post_datetime.does_not_exist()):
print("Scanned item: {0} {1}".format(item.subject, item.views))
print(f"Scanned item: {item.subject} {item.views}")

# Conditionally save an item
thread_item = Thread(
Expand Down Expand Up @@ -204,7 +204,7 @@ class Meta:

# Backup/restore example
# Print the size of the table
print("Table size: {}".format(Thread.describe_table().get('ItemCount')))
print(f"Table size: {Thread.describe_table().get('ItemCount')}")

# Dump the entire table to a file
Thread.dump('thread.json')
Expand All @@ -213,11 +213,11 @@ class Meta:
# Commented out for safety
# for item in Thread.scan():
# item.delete()
print("Table size: {}".format(Thread.describe_table().get('ItemCount')))
print(f"Table size: {Thread.describe_table().get('ItemCount')}")

# Restore table from a file
Thread.load('thread.json')
print("Table size: {}".format(Thread.describe_table().get('ItemCount')))
print(f"Table size: {Thread.describe_table().get('ItemCount')}")

# Dump the entire table to a string
serialized = Thread.dumps()
Expand Down
38 changes: 19 additions & 19 deletions pynamodb/attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def get_value(self, value: Dict[str, Any]) -> Any:

def __iter__(self):
# Because we define __getitem__ below for condition expression support
raise TypeError("'{}' object is not iterable".format(self.__class__.__name__))
raise TypeError(f"'{self.__class__.__name__}' object is not iterable")

# Condition Expression Support
def __eq__(self, other: Any) -> 'Comparison': # type: ignore
Expand Down Expand Up @@ -264,7 +264,7 @@ def _initialize_attributes(cls, discriminator_value):
raise NotImplementedError("Discriminators are not yet supported in model classes.")
if discriminator_value is not None:
if not cls._discriminator:
raise ValueError("{} does not have a discriminator attribute".format(cls.__name__))
raise ValueError(f"{cls.__name__} does not have a discriminator attribute")
cls._attributes[cls._discriminator].register_class(cls, discriminator_value)


Expand Down Expand Up @@ -338,7 +338,7 @@ def _set_attributes(self, **attributes: Attribute) -> None:
"""
for attr_name, attr_value in attributes.items():
if attr_name not in self.get_attributes():
raise ValueError("Attribute {} specified does not exist".format(attr_name))
raise ValueError(f"Attribute {attr_name} specified does not exist")
setattr(self, attr_name, attr_value)

def _serialize(self, null_check=True) -> Dict[str, Dict[str, Any]]:
Expand All @@ -349,11 +349,11 @@ def _serialize(self, null_check=True) -> Dict[str, Dict[str, Any]]:
for name, attr in self.get_attributes().items():
value = getattr(self, name)
if isinstance(value, MapAttribute) and not value.validate():
raise ValueError("Attribute '{}' is not correctly typed".format(name))
raise ValueError(f"Attribute '{name}' is not correctly typed")

attr_value = attr.serialize(value) if value is not None else None
if null_check and attr_value is None and not attr.null:
raise ValueError("Attribute '{}' cannot be None".format(name))
raise ValueError(f"Attribute '{name}' cannot be None")

if attr_value is not None:
attribute_values[attr.attr_name] = {attr.attr_type: attr_value}
Expand Down Expand Up @@ -405,7 +405,7 @@ def get_discriminator(self, cls: type) -> Optional[Any]:
return self._class_map.get(cls)

def __set__(self, instance: Any, value: Optional[type]) -> None:
raise TypeError("'{}' object does not support item assignment".format(self.__class__.__name__))
raise TypeError(f"'{self.__class__.__name__}' object does not support item assignment")

def serialize(self, value):
"""
Expand All @@ -418,7 +418,7 @@ def deserialize(self, value):
Returns the class corresponding to the given discriminator value.
"""
if value not in self._discriminator_map:
raise ValueError("Unknown discriminator value: {}".format(value))
raise ValueError(f"Unknown discriminator value: {value}")
return self._discriminator_map[value]


Expand Down Expand Up @@ -678,14 +678,14 @@ def _fast_parse_utc_date_string(date_string: str) -> datetime:
if (len(date_string) != 31 or date_string[4] != '-' or date_string[7] != '-'
or date_string[10] != 'T' or date_string[13] != ':' or date_string[16] != ':'
or date_string[19] != '.' or date_string[26:31] != '+0000'):
raise ValueError("Datetime string '{}' does not match format '{}'".format(date_string, DATETIME_FORMAT))
raise ValueError(f"Datetime string '{date_string}' does not match format '{DATETIME_FORMAT}'")
return datetime(
_int(date_string[0:4]), _int(date_string[5:7]), _int(date_string[8:10]),
_int(date_string[11:13]), _int(date_string[14:16]), _int(date_string[17:19]),
_int(date_string[20:26]), timezone.utc
)
except (TypeError, ValueError):
raise ValueError("Datetime string '{}' does not match format '{}'".format(date_string, DATETIME_FORMAT))
raise ValueError(f"Datetime string '{date_string}' does not match format '{DATETIME_FORMAT}'")


class NullAttribute(Attribute[None]):
Expand Down Expand Up @@ -838,17 +838,17 @@ def __getitem__(self, item: _KT) -> _VT: # type: ignore
elif item in self._attributes: # type: ignore
return getattr(self, item)
else:
raise AttributeError("'{}' has no attribute '{}'".format(self.__class__.__name__, item))
raise AttributeError(f"'{self.__class__.__name__}' has no attribute '{item}'")

def __setitem__(self, item, value):
if not self._is_attribute_container():
raise TypeError("'{}' object does not support item assignment".format(self.__class__.__name__))
raise TypeError(f"'{self.__class__.__name__}' object does not support item assignment")
if self.is_raw():
self.attribute_values[item] = value
elif item in self._attributes: # type: ignore
setattr(self, item, value)
else:
raise AttributeError("'{}' has no attribute '{}'".format(self.__class__.__name__, item))
raise AttributeError(f"'{self.__class__.__name__}' has no attribute '{item}'")

def __getattr__(self, attr: str) -> _VT:
# This should only be called for "raw" (i.e. non-subclassed) MapAttribute instances.
Expand All @@ -858,7 +858,7 @@ def __getattr__(self, attr: str) -> _VT:
return self.attribute_values[attr]
except KeyError:
pass
raise AttributeError("'{}' has no attribute '{}'".format(self.__class__.__name__, attr))
raise AttributeError(f"'{self.__class__.__name__}' has no attribute '{attr}'")

@overload # type: ignore
def __get__(self: _A, instance: None, owner: Any) -> _A: ...
Expand Down Expand Up @@ -897,7 +897,7 @@ def is_correctly_typed(self, key, attr):
if can_be_null and value is None:
return True
if getattr(self, key) is None:
raise ValueError("Attribute '{}' cannot be None".format(key))
raise ValueError(f"Attribute '{key}' cannot be None")
return True # TODO: check that the actual type of `value` meets requirements of `attr`

def validate(self):
Expand Down Expand Up @@ -974,7 +974,7 @@ def _get_class_for_serialize(value):
return value
value_type = type(value)
if value_type not in SERIALIZE_CLASS_MAP:
raise ValueError('Unknown value: {}'.format(value_type))
raise ValueError(f'Unknown value: {value_type}')
return SERIALIZE_CLASS_MAP[value_type]


Expand Down Expand Up @@ -1011,7 +1011,7 @@ def serialize(self, values):
for v in values:
attr_class = self._get_serialize_class(v)
if self.element_type and v is not None and not isinstance(attr_class, self.element_type):
raise ValueError("List elements must be of type: {}".format(self.element_type.__name__))
raise ValueError(f"List elements must be of type: {self.element_type.__name__}")
attr_type = attr_class.attr_type
attr_value = attr_class.serialize(v)
if attr_value is None:
Expand All @@ -1034,7 +1034,7 @@ def deserialize(self, values):
value = None
if NULL not in attribute_value:
# set attr_name in case `get_value` raises an exception
element_attr.attr_name = '{}[{}]'.format(self.attr_name, idx)
element_attr.attr_name = f'{self.attr_name}[{idx}]'
value = element_attr.deserialize(element_attr.get_value(attribute_value))
deserialized_lst.append(value)
return deserialized_lst
Expand All @@ -1046,15 +1046,15 @@ def deserialize(self, values):

def __getitem__(self, idx: int) -> Path: # type: ignore
if not isinstance(idx, int):
raise TypeError("list indices must be integers, not {}".format(type(idx).__name__))
raise TypeError(f"list indices must be integers, not {type(idx).__name__}")

if self.element_type:
# If this instance is typed, return a properly configured attribute on list element access.
element_attr = self.element_type()
if isinstance(element_attr, MapAttribute):
element_attr._make_attribute()
element_attr.attr_path = list(self.attr_path) # copy the document path before indexing last element
element_attr.attr_name = '{}[{}]'.format(element_attr.attr_name, idx)
element_attr.attr_name = f'{element_attr.attr_name}[{idx}]'
if isinstance(element_attr, MapAttribute):
for path_segment in reversed(element_attr.attr_path):
element_attr._update_attribute_paths(path_segment)
Expand Down
Loading