Skip to content

Commit

Permalink
Refactor internal functions (#910)
Browse files Browse the repository at this point in the history
* Fix invalid rst in docs/index.rst

* Fix features section

* Fix sidebar for mimesis.name

* Remove www. from social_media_profile

* Replace .format with + in Person.email

* Add __call__ of AbstractField to docs

* Rename schoice to generate_string

* Eliminate code duplication

* Rename internal function pull to _pull
  • Loading branch information
lk-geimfari committed Jul 17, 2020
1 parent 2b68e4c commit a273284
Show file tree
Hide file tree
Showing 19 changed files with 48 additions and 49 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.rst
Expand Up @@ -17,6 +17,8 @@ Version 5.0.0
**Rename**:

- Renamed ``decorators.romanized`` to ``decorators.romanize``
- Renamed ``Random.schoice`` to ``Random.generate_string``
- Renamed ``BaseDataProvider.pull`` to ``BaseDataProvider._pull``

**Removed**:

Expand Down Expand Up @@ -343,7 +345,7 @@ is no backwards compatibility with early versions of this library.
- Added ``price_in_btc`` and ``currency_symbol`` to ``Business`` data provider
- Added ``dna``, ``rna`` and ``atomic_number`` to ``Science`` data provider
- Added ``vehicle_registration_code`` to ``Transport`` data provider
- Added ``schoice`` method for ``Random``
- Added ``generate_string`` method for ``Random``
- Added alias ``last_name`` for ``surname`` in ``Personal`` data provider
- Added alias ``province``, ``region``, ``federal_subject`` for ``state`` in ``Address`` data provider
- Added annotations for all methods and functions for supporting type hints
Expand Down
2 changes: 1 addition & 1 deletion README.rst
Expand Up @@ -204,7 +204,7 @@ How to Contribute
3. Fork the repository on GitHub to start making your changes to the
*your_branch* branch.
4. Add yourself to the list of `contributors`_.
5. Send a pull request and bug the maintainer until it gets merged and
5. Send a _pull request and bug the maintainer until it gets merged and
published.

.. _contributing guidelines: https://github.com/lk-geimfari/mimesis/blob/master/CONTRIBUTING.rst
Expand Down
1 change: 1 addition & 0 deletions docs/api.rst
Expand Up @@ -317,6 +317,7 @@ AbstractField

.. autoclass:: mimesis.schema.AbstractField
:members:
:special-members: __call__

Field
------
Expand Down
2 changes: 1 addition & 1 deletion mimesis/builtins/de.py
Expand Up @@ -14,7 +14,7 @@ class GermanySpecProvider(BaseSpecProvider):
def __init__(self, seed: Seed = None):
"""Initialize attributes."""
super().__init__(locale='de', seed=seed)
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""The name of the provider."""
Expand Down
2 changes: 1 addition & 1 deletion mimesis/builtins/it.py
Expand Up @@ -18,7 +18,7 @@ class ItalySpecProvider(BaseSpecProvider):
def __init__(self, seed: Seed = None):
"""Initialize attributes."""
super().__init__(locale='it', seed=seed)
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""The name of the provider."""
Expand Down
2 changes: 1 addition & 1 deletion mimesis/builtins/ru.py
Expand Up @@ -15,7 +15,7 @@ class RussiaSpecProvider(BaseSpecProvider):
def __init__(self, seed: Seed = None):
"""Initialize attributes."""
super().__init__(locale='ru', seed=seed)
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""The name of the provider."""
Expand Down
2 changes: 1 addition & 1 deletion mimesis/builtins/uk.py
Expand Up @@ -15,7 +15,7 @@ class UkraineSpecProvider(BaseSpecProvider):
def __init__(self, seed: Seed = None):
"""Initialize attributes."""
super().__init__(locale='uk', seed=seed)
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""The name of the provider."""
Expand Down
2 changes: 1 addition & 1 deletion mimesis/providers/address.py
Expand Up @@ -34,7 +34,7 @@ def __init__(self, *args, **kwargs) -> None:
"""
super().__init__(*args, **kwargs)
self._datafile = 'address.json'
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""Class for metadata."""
Expand Down
8 changes: 4 additions & 4 deletions mimesis/providers/base.py
Expand Up @@ -81,7 +81,7 @@ def __init__(self, locale: str = locales.DEFAULT_LOCALE,
:param seed: Seed to all the random functions.
"""
super().__init__(seed=seed)
self._data: Dict[str, Any] = {}
self._data: JSON = {}
self._datafile = ''
self._setup_locale(locale)
self._data_dir = Path(__file__).parent.parent.joinpath('data')
Expand Down Expand Up @@ -118,7 +118,7 @@ def _update_dict(self, initial: JSON, other: Mapping) -> JSON:
return initial

@functools.lru_cache(maxsize=None)
def pull(self, datafile: str = '') -> None:
def _pull(self, datafile: str = '') -> None:
"""Pull the content from the JSON and memorize one.
Opens JSON file ``file`` in the folder ``data/locale``
Expand Down Expand Up @@ -171,8 +171,8 @@ def _override_locale(self, locale: str = locales.DEFAULT_LOCALE) -> None:
:return: Nothing.
"""
self.locale = locale
self.pull.cache_clear()
self.pull()
self._pull.cache_clear()
self._pull()

@contextlib.contextmanager
def override_locale(self, locale: str = locales.EN,
Expand Down
2 changes: 1 addition & 1 deletion mimesis/providers/business.py
Expand Up @@ -23,7 +23,7 @@ def __init__(self, *args, **kwargs):
"""
super().__init__(*args, **kwargs)
self._datafile = 'business.json'
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""Class for metadata."""
Expand Down
2 changes: 1 addition & 1 deletion mimesis/providers/date.py
Expand Up @@ -27,7 +27,7 @@ def __init__(self, *args, **kwargs):
"""
super().__init__(*args, **kwargs)
self._datafile = 'datetime.json'
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""Class for metadata."""
Expand Down
2 changes: 1 addition & 1 deletion mimesis/providers/food.py
Expand Up @@ -17,7 +17,7 @@ def __init__(self, *args, **kwargs):
"""
super().__init__(*args, **kwargs)
self._datafile = 'food.json'
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""Class for metadata."""
Expand Down
9 changes: 4 additions & 5 deletions mimesis/providers/person.py
Expand Up @@ -4,7 +4,6 @@

import hashlib
import re
import uuid
from string import ascii_letters, digits, punctuation
from typing import Optional, Union

Expand Down Expand Up @@ -36,7 +35,7 @@ def __init__(self, *args, **kwargs) -> None:
"""
super().__init__(*args, **kwargs)
self._datafile = 'person.json'
self.pull(self._datafile)
self._pull(self._datafile)
self._store = {
'age': 0,
}
Expand Down Expand Up @@ -263,10 +262,10 @@ def email(self, domains: Union[tuple, list] = None,
domain = self.random.choice(domains)

if not domain.startswith('@'):
domain = '@{}'.format(domain)
domain = '@' + domain

if unique:
name = uuid.uuid4().hex
name = self.random.randstr(unique)
else:
name = self.username(template='ld')

Expand All @@ -286,7 +285,7 @@ def social_media_profile(self,
"""
key = self._validate_enum(site, SocialNetwork)
website = SOCIAL_NETWORKS[key]
url = 'https://www.' + website
url = 'https://' + website
return url.format(self.username())

def gender(self, iso5218: bool = False,
Expand Down
6 changes: 3 additions & 3 deletions mimesis/providers/science.py
Expand Up @@ -20,7 +20,7 @@ def __init__(self, *args, **kwargs):
"""
super().__init__(*args, **kwargs)
self._datafile = 'science.json'
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""Class for metadata."""
Expand Down Expand Up @@ -68,7 +68,7 @@ def rna_sequence(self, length: int = 10) -> str:
:Example:
AGUGACACAA
"""
return self.random.schoice('UCGA', length)
return self.random.generate_string('UCGA', length)

def dna_sequence(self, length: int = 10) -> str:
"""Generate a random DNA sequence.
Expand All @@ -79,4 +79,4 @@ def dna_sequence(self, length: int = 10) -> str:
:Example:
GCTTTAGACC
"""
return self.random.schoice('TCGA', length)
return self.random.generate_string('TCGA', length)
2 changes: 1 addition & 1 deletion mimesis/providers/text.py
Expand Up @@ -21,7 +21,7 @@ def __init__(self, *args, **kwargs):
"""
super().__init__(*args, **kwargs)
self._datafile = 'text.json'
self.pull(self._datafile)
self._pull(self._datafile)

class Meta:
"""Class for metadata."""
Expand Down
12 changes: 5 additions & 7 deletions mimesis/random.py
Expand Up @@ -53,16 +53,14 @@ def urandom(*args: Any, **kwargs: Any) -> bytes:
"""
return os.urandom(*args, **kwargs)

def schoice(self, seq: str, end: int = 10) -> str:
"""Choice function which returns string created from sequence.
def generate_string(self, str_seq: str, length: int = 10) -> str:
"""Generate random string created from string sequence.
:param seq: Sequence of letters or digits.
:type seq: tuple or list
:param end: Max value.
:param str_seq: String sequence of letters or digits.
:param length: Max value.
:return: Single string.
"""
return ''.join(self.choice(list(seq))
for _ in range(end))
return ''.join(self.choice(str_seq) for _ in range(length))

def custom_code(self, mask: str = '@###',
char: str = '@', digit: str = '#') -> str:
Expand Down
27 changes: 13 additions & 14 deletions mimesis/schema.py
Expand Up @@ -23,12 +23,9 @@ class AbstractField(object):
Instance of this object takes any string which represents name
of any method of any supported data provider (:class:`~mimesis.Generic`)
and the ``**kwargs`` of the method:
and the ``**kwargs`` of the method.
>>> _ = AbstractField('en', 0xf)
>>> surname = _('surname')
>>> isinstance(surname, str)
True
See :class:`~mimesis.schema.AbstractField.__call__` for more details.
"""

def __init__(self, locale: str = 'en',
Expand All @@ -52,17 +49,19 @@ def __call__(self, name: Optional[str] = None,
key: Optional[Callable] = None, **kwargs) -> Any:
"""Override standard call.
This magic method override standard call so it's take any string which
represents name of the any method of any supported data provider
and the ``**kwargs`` of this method.
This magic method overrides standard call so it takes any string
which represents the name of any method of any supported data
provider and the ``**kwargs`` of this method.
..note:: Some data providers have methods with the same name and
in such cases, you can explicitly define that the method belongs to
data-provider ``name='provider.name'``.
.. note:: Some data providers have methods with the same names
and in such cases, you can explicitly define that the method
belongs to data-provider ``name='provider.name'`` otherwise
it will return the data from the first provider which
has a method ``name``.
You can apply a *key function* to result returned by the method,
to do it, just pass parameter **key** with a callable object which
returns final result.
You can apply a *key function* to the result returned by
the method, bt passing a parameter **key** with a callable
object which returns the final result.
:param name: Name of the method.
:param key: A key function (or other callable object)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_providers/test_base.py
Expand Up @@ -55,14 +55,14 @@ def test_override_locale_independent(self, provider):
)
def test_pull(self, locale, city):
data_provider = BaseDataProvider(locale)
data_provider.pull('address.json')
data_provider._pull('address.json')
assert city in data_provider._data['city']

@pytest.mark.parametrize('locale', LIST_OF_LOCALES)
def test_pull_raises(self, locale):
data_provider = BaseDataProvider(locale=locale)
with pytest.raises(FileNotFoundError):
data_provider.pull('something.json')
data_provider._pull('something.json')

def test_update_dict(self, base_data_provider):
first = {
Expand Down
6 changes: 3 additions & 3 deletions tests/test_random.py
Expand Up @@ -37,13 +37,13 @@ def test_urandom(random, n):


@pytest.mark.parametrize(
'seq, length', [
'str_seq, length', [
('U', 10),
('A', 20),
],
)
def test_schoice(random, seq, length):
result = random.schoice(seq, length)
def test_generate_string(random, str_seq, length):
result = random.generate_string(str_seq, length)
assert len(result) == length


Expand Down

0 comments on commit a273284

Please sign in to comment.