pycharmers.utils.generic_utils module

pycharmers.utils.generic_utils.handleKeyError(lst, **kwargs)[source]

Check whether all kwargs.values() in the lst.

Parameters
  • lst (list) – candidates.

  • kwargskey is the varname that is easy to understand when an error occurs

Examples

>>> from pycharmers.utils import handleKeyError
>>> handleKeyError(lst=range(3), val=1)
>>> handleKeyError(lst=range(3), val=100)
KeyError: Please choose the argment val from ['0', '1', '2']. you chose 100
>>> handleKeyError(lst=range(3), val1=1, val2=2)
>>> handleKeyError(lst=range(3), val1=1, val2=100)
KeyError: Please choose the argment val2 from ['0', '1', '2']. you chose 100
Raises

KeyError – If kwargs.values() not in the lst

pycharmers.utils.generic_utils.class2str(class_)[source]

Convert class to str.

Parameters

class (class) – class object

Examples

>>> from pycharmers.utils import class2str
>>> class2str(str)
'str'
>>> class2str(tuple)
'tuple'
pycharmers.utils.generic_utils.handleTypeError(types=[], **kwargs)[source]

Check whether all types of kwargs.values() match any of types.

Parameters
  • types (list) – Candidate types.

  • kwargskey is the varname that is easy to understand when an error occurs

Examples

>>> from pycharmers.utils import handleTypeError
>>> handleTypeError(types=[str], val="foo")
>>> handleTypeError(types=[str, int], val=1)
>>> handleTypeError(types=[str, int], val=1.)
TypeError: val must be one of ['str', 'int'], not float
>>> handleTypeError(types=[str], val1="foo", val2="bar")
>>> handleTypeError(types=[str, int], val1="foo", val2=1.)
TypeError: val2 must be one of ['str', 'int'], not float
Raises

TypeError – If the types of kwargs.values() are none of the types

pycharmers.utils.generic_utils.str_strip(string)[source]

Convert all consecutive whitespace characters to ‘ ‘ (half-width whitespace), then return a copy of the string with leading and trailing whitespace removed.

Parameters

string (str) – string

Example

>>> from pycharmers.utils import str_strip
>>> str_strip(" hoge   ")
'hoge'
>>> str_strip(" ho    ge   ")
'ho ge'
>>> str_strip("  ho    g e")
'ho g e'
pycharmers.utils.generic_utils.now_str(tz=None, fmt='%Y-%m-%d@%H.%M.%S')[source]

Returns new datetime string representing current time local to tz under the control of an explicit format string.

Parameters
  • tz (Optional[datetime.timezone], optional) – Timezone object. If no tz is specified, uses local timezone. Defaults to None.

  • fmt (str, optional) – A format string. See Python Documentation. Defaults to "%Y-%m-%d@%H.%M.%S".

Returns

A datetime string representing current time local to tz.

Return type

str

Example

>>> from pycharmers.utils import now_str
>>> now_str()
'2020-09-14@22.31.17'
>>> now_str(fmt="%A, %d. %B %Y %I:%M%p")
Monday, 14. September 2020 10:31PM'
>>> now_str(tz=datetime.timezone.utc)
'2020-09-14@13.31.17'
pycharmers.utils.generic_utils.list_transpose(lst, width)[source]

Transpose a list.

Parameters
  • lst (list) – A single list.

  • width (int) – The width of the list.

Notes: Perform the following conversion:

----------->      0, 4,  8 |
0, 1,  2,  3      1, 5,  9 |
4, 5,  6,  7  ->  2, 6, 10 |
8, 9, 10, 11      3, 7, 11 v

Example

>>> from pyutils.utils import list_transpose
>>> lst = [i for i in range(10)]
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list_transpose(lst, width=3)
[0, 3, 6, 9, 1, 4, 7, 2, 5, 8]
>>> list_transpose(lst, width=4)
[0, 4, 8, 1, 5, 9, 2, 6, 3, 7]
pycharmers.utils.generic_utils.flatten_dual(lst)[source]

Flatten double list.

Parameters

lst (list) – Dual list.

Example

>>> from pycharmers.utils import flatten_dual
>>> flatten_dual([[1,2,3],[4,5,6]])
[1, 2, 3, 4, 5, 6]
>>> flatten_dual([[[1,2,3]],[4,5,6]])
[[1, 2, 3], 4, 5, 6]
>>> flatten_dual(flatten_dual([[[1,2,3]],[4,5,6]]))
TypeError: 'int' object is not iterable
Raises

TypeError – If list is not a dual list.

pycharmers.utils.generic_utils.calc_rectangle_size(area, w=None)[source]

Calculate the lengths of the sides of the rectangle from the area and the vertical length (width).

Parameters
  • area (int) – The area of the rectangle.

  • w (int) – The length of the vertical line. (width) If w is None, arrange like a square.

Returns

(w, h)

The tuple of the lengths of horizontal, and vertical lines. (width, height)

Return type

size (tuple)

Examples

>>> from pycharmers.utils import calc_rectangle
>>> calc_rectangle(12, 3)
(3, 4)
>>> calc_rectangle(12, 18)
(12, 1)
>>> calc_rectangle(12, 7)
(7, 2)
pycharmers.utils.generic_utils.readable_bytes(size, type='bytes')[source]

Unit conversion for readability.

Parameters

size (int) – File size expressed in bytes

Examples

>>> from pycharmers.utils import readable_bytes
>>> size, unit = readable_bytes(1e2)
>>> print(f"{size:.2f}[{unit}]")
100.00[KB]
>>> size, unit = readable_bytes(1e5)
>>> print(f"{size:.2f}[{unit}]")
97.66[MB]
>>> size, unit = readable_bytes(1e10)
>>> print(f"{size:.2f}[{unit}]")
9.31[GB]
pycharmers.utils.generic_utils.get_create(corresp_dict={}, class_=[], genre='', name='Python-Charmers')[source]

Create a get functions

Parameters
  • corresp_dict (dict) – Dictionary of identifier -> instance

  • class (list) – The list of class names.

  • genre (str) – Genre of the class.

  • name (str) – Package name.

Examples

>>> import cv2
>>> from pycharmers.utils import get_create
>>> all = PYCHARMERS_BACKGROUND_SUBTRACTOR_CREATORS = {
...     "mog" : cv2.createBackgroundSubtractorMOG2,
...     "knn" : cv2.createBackgroundSubtractorKNN,
... }
>>> background_subtractor_create = get_create(corresp_dict=all, class_=[cv2.BackgroundSubtractor], genre="background_subtractor")
pycharmers.utils.generic_utils.pycat(file, head=- 1, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, count_number=False)[source]

Display the contents of the specified file.

Parameters
  • head (int) –

  • mode (str) – The mode in which the file is opened.

  • buffering (int) – Set the buffering policy.

  • encoding (str) – Name of the encoding used to encode the file.

  • errors (str) – How encoding errors are to be handled.

  • newline (str) – How universal newlines works (it only applies to text mode)

  • count_number (bool) – Whether to display line number.

Examples

>>> from pycharmers.opencv import SAMPLE_LENA_IMG
>>> from pycharmers.utils import pycat
>>> pycat(SAMPLE_LENA_IMG, mode="rb")
pycharmers.utils.generic_utils.pytree(*args, pattern='**/*', disp_all=False, max_level=- 1, **kwargs)[source]

list contents of directories in a tree-like format.

Parameters
  • *args/**kwargs

    Argments for root = Path(*args, **kwargs)

  • pattern (str) – Argments for root.glob(pattern)

  • disp_all (bool) – Whether not to ignore entries starting with .

  • max_level (int) – Max display depth of the directory tree.

Examples

>>> from pycharmers.utils import pytree
>>> from pycharmers.utils._path import REPO_DIR
>>> pytree(REPO_DIR, pattern="**/*.py", max_level=3)
/Users/iwasakishuto/Github/portfolio/Python-Charmers
├── build
│   └── lib
│       └── pycharmers
├── develop
│   ├── colorbar.py
│   ├── cvCascade.old.py
│   ├── drawing.py
│   ├── drawingpad.py
│   └── monitor.py
class pycharmers.utils.generic_utils.formatted_enumerator(iterable, start=1)[source]

Bases: object

Generator which yeilds elements with formatted numbers.

Parameters
  • iterable (int) – An object supporting iteration

  • start (int) – The enumerate object yields pairs containing a count (from start, which defaults to 1) and a value yielded by the iterable argument.

total

Total number of iterable elements.

Type

int

digit

Digit. It is used for formatting the index.

Type

int

Examples

>>> from pycharmers.utils import formatted_enumerator
>>> gen = formatted_enumerator(["a","b","c"])
>>> for i,d in gen:
...     print(i, d)
1 a
2 i
3 u
pycharmers.utils.generic_utils.open_new_tab(url)[source]

Open url in a new page (“tab”) of the default browser.

Parameters

url (str) – Local file path or url.

Returns

Whether it was successful or not.

Return type

flag (bool)

Examples

>>> from pycharmers.utils import open_new_tab
>>> open_new_tab("https://google.com")
True
>>> open_new_tab("sample.html")
True
pycharmers.utils.generic_utils.remove_invalid_fn(fn)[source]

Remove invalid file name.

Parameters

fn (str) – filename

Example

>>> from pycharmers.utils import remove_invalid_fn
>>> remove_invalid_fn(fn="Is plasticity of synapses the mechanism of long-term memory storage?")
'Is plasticity of synapses the mechanism of long-term memory storage'
>>> remove_invalid_fn(fn="siDirect 2.0: updated software for designing functional siRNA with reduced seed-dependent off-target effect")
'siDirect 2.0 updated software for designing functional siRNA with reduced seed-dependent off-target effect'
pycharmers.utils.generic_utils.try_wrapper(func, *args, ret_=None, msg_='', verbose_=True, **kwargs)[source]

Wrap func(*args, **kwargs) with try- and except blocks.

Parameters
  • func (functions) – functions.

  • args (tuple) – *args for func.

  • kwargs (kwargs) – *kwargs for func.

  • ret (any) – default ret val.

  • msg (str) – message to print.

  • verbose (bool) – Whether to print message or not. (default= True)

Examples

>>> from pycharmers.utils import try_wrapper
>>> ret = try_wrapper(lambda x,y: x/y, 1, 2, msg_="divide")
Succeeded to divide
>>> ret
0.5
>>> ret = try_wrapper(lambda x,y: x/y, 1, 0, msg_="divide")
[division by zero] Failed to divide
>>> ret is None
True
>>> ret = try_wrapper(lambda x,y: x/y, 1, 0, ret_=1, msg_="divide")
>>> ret is None
False
>>> ret
1
pycharmers.utils.generic_utils.list2name(lst, how='snake')[source]

Naming convention.

Parameters
  • lst (list) – List.

  • how (str) – How to convert list elements to string name.

Examples

>>> from pycharmers.utils import list2name
>>> list2name(lst=["iwasaki", "shuto"], how="camel")
'iwasakiShuto'
>>> list2name(lst=["iwasaki", "shuto"], how="pascal")
'IwasakiShuto'
>>> list2name(lst=["iwasaki", "shuto"], how="snake")
'iwasaki_shuto'
>>> list2name(lst=["iwasaki", "shuto"], how="kebab")
'iwasaki-shuto'
pycharmers.utils.generic_utils.infer_types(val, default=<class 'str'>)[source]

Infer data types by evaluate the given source.

Parameters
  • val (str) – data

  • default (type) – Default type.

Returns

data type.

Return type

type (type)

Examples

>>> from pycharmers.utils import infer_types
>>> infer_types(1)
int
>>> infer_types(1.1)
float
>>> infer_types("1e3")
float
>>> infer_types("Hello")
str
pycharmers.utils.generic_utils.html2reStructuredText(html, base_url='')[source]

Convert html string to reStructuredText

Parameters
  • html (str) – html string.

  • base_url (str) – base URL.

Returns

reStructuredText.

Return type

reStructuredText (str)

Examples

>>> from pycharmers.utils import html2reStructuredText
>>> html2reStructuredText("<code>CODE</code>")
' ``CODE`` '
>>> html2reStructuredText(
...     html='<a class="reference internal" href="pycharmers.html">pycharmers package</a>',
...     base_url="https://iwasakishuto.github.io/Python-Charmers/"
>>> )
'`pycharmers package <https://iwasakishuto.github.io/Python-Charmers/pycharmers.html>`_'
pycharmers.utils.generic_utils.int2ordinal(num)[source]

Convert a natural number to a ordinal number.

Parameters

num (int) – natural number

Returns

ordinal number, like 0th, 1st, 2nd,…

Return type

str

Examples

>>> from pycharmers.utils import int2ordinal
>>> int2ordinal(0)
'0th'
>>> int2ordinal(1)
'1st'
>>> int2ordinal(2)
'2nd'
>>> int2ordinal(3)
'3rd'
>>> int2ordinal(4)
'4th'
>>> int2ordinal(11)
'11th'
>>> int2ordinal(21)
'21st'
>>> int2ordinal(111)
'111th'
>>> int2ordinal(121)
'121st'
pycharmers.utils.generic_utils.filenaming(name=None)[source]

Avoid having the same name as an existing file.

Parameters

name (str) – File name you want to name

Returns

File name that is not the same name as an existing file.

Return type

str

Examples

>>> import os
>>> from pycharmers.utils import filenaming
>>> print(os.listdir())
['Untitled.ipynb', 'Untitled(1).ipynb', 'Untitled(3).ipynb']
>>> filenaming("Untitled.ipynb")
'./Untitled(2).ipynb'
>>> filenaming("Untitled.py")
'Untitled.py'
pycharmers.utils.generic_utils.get_pyenv(scope_variables)[source]

In what environment python is running.

Parameters

scope_variables (dict) – the dictionary containing the current scope’s global (local) variables. ( globals() or locals() )

Returns

wheather the environment is Jupyter Notebook or not.

Return type

str

Examples

>>> from pycharmers.utils import get_pyenv
>>> get_pyenv(globals())
'Jupyter Notebook'

Todo

Execute this function without arguments.

pycharmers.utils.generic_utils.assign_trbl(data, name, default=None)[source]

Return the name ‘s values of [Top, Right, Bottom, Left] from data

Parameters
  • data (dict) – Data Dictionary.

  • name (str) – The name of the value you want to assign.

  • default – Default Value.

Returns

Values of Top, Right, Bottom, Left

Return type

tuple

Examples

>>> from pycharmers.utils import assign_trbl
>>> assign_trbl(data={"margin": [1,2,3,4]}, name="margin")
(1, 2, 3, 4)
>>> assign_trbl(data={"margin": [1,2,3]}, name="margin")
(1, 2, 3, 2)
>>> assign_trbl(data={"margin": [1,2]}, name="margin")
(1, 2, 1, 2)
>>> assign_trbl(data={"margin": 1}, name="margin")
(1, 1, 1, 1)
>>> assign_trbl(data={"margin": 1}, name="padding", default=5)
(5, 5, 5, 5)
pycharmers.utils.generic_utils.relative_import(f, i, absfile, name)[source]

Relative import that can be used with script files such as those executed by python commands

Parameters
  • f (str) – "XXX" of from XXX

  • i (str) – "YYY" of import YYY

  • absfile (str) – os.path.abspath(__file__)

  • name (str) – __name__

Returns

exec(i)

Return type

Object

Examples

>>> import os
>>> from pycharmers.utils import relative_import
>>> relative_import(f="..utils", i="LeNet", absfile=os.path.abspath(__file__), name=__name__)
pycharmers.utils.generic_utils.verbose2print(verbose=True)[source]

Create a simple print function based on verbose

Parameters

verbose (bool) – Whether to print or not.

Returns

Print function

Return type

function

Examples

>>> from pycharmers.utils import verbose2print
>>> print_verbose = verbose2print(verbose=True)
>>> print_non_verbose = verbose2print(verbose=False)
>>> print_verbose("Hello, world.")
Hello, world.
>>> print_non_verbose = verbose2print("Hello, world.")
pycharmers.utils.generic_utils.get_random_ttfontname(random_state: Optional[int] = None) → str[source]

Get a ttfont randomly from fonts installed on your system.

Parameters

random_state (Optional[int], optional) – Random State. Defaults to None.

Returns

Path to the ttfont.

Return type

str

Examples

>>> from pycharmers.utils import get_random_ttfontname
>>> get_random_ttfontname()
'/System/Library/Fonts/ArialHB.ttc'
>>> get_random_ttfontname()
'/System/Library/Fonts/AppleSDGothicNeo.ttc'
>>> get_random_ttfontname(0)
'/System/Library/Fonts/Palatino.ttc'
>>> get_random_ttfontname(0)
'/System/Library/Fonts/Palatino.ttc'
pycharmers.utils.generic_utils.html_decode(s: str) → str[source]

Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like <p>.

Parameters

s (str) – HTML string.

Returns

ASCII decoded string.

Return type

str

Examples

>>> from pycharmers.utils import html_decode
>>> html_decode('>>> print("Hello, world!")')
'>>> print("Hello, world!")'
>>> html_decode('&gt;&gt;&gt; print("Hello, world!")')
'>>> print("Hello, world!")'
pycharmers.utils.generic_utils.split_code(code: str, lexer: pygments.lexer.Lexer = <pygments.lexers.PythonLexer>) → List[List[str]][source]

Split code based on code higlighting.

Parameters
  • code (str) – A programming code.

  • lexer (Lexer, optional) – A Lexer for a specific language. Defaults to PythonLexer().

Returns

A dual list of code and class. [[code,class]].

Return type

List[List[str,str]]

Examples

>>> from pycharmers.utils import split_code
>>> splitted_code = split_code("""
... >>> try:
... ...     from iwasakishuto import portfolio
... >>> except ModuleNotFoundError:
... ...     print(f"Nice to meet you :)")
... >>> portfolio.load()
>>> """)
>>> for code,cls in splitted_code:
...     print(code, end="")