stdl 0.5.2__tar.gz → 0.5.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stdl
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: Extended Python Standard Library
5
5
  Author-email: Žiga Ivanšek <ziga.ivansek@gmail.com>
6
6
  Project-URL: Repository, https://github.com/zigai/stdl
7
+ Project-URL: Documentation, https://stdl.readthedocs.io
7
8
  Keywords: python utilites,filesystem,string manipulation,logging configuration,list utils,standard library,ANSI colors,terminal output
8
9
  Classifier: Intended Audience :: Developers
9
10
  Classifier: License :: OSI Approved :: MIT License
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "stdl"
3
- version = "0.5.2"
3
+ version = "0.5.4"
4
4
  description = "Extended Python Standard Library"
5
5
  authors = [{ name = "Žiga Ivanšek", email = "ziga.ivansek@gmail.com" }]
6
6
  license = { file = "LICENSE.txt" }
@@ -52,6 +52,7 @@ dev = [
52
52
 
53
53
  [project.urls]
54
54
  Repository = "https://github.com/zigai/stdl"
55
+ Documentation = "https://stdl.readthedocs.io"
55
56
 
56
57
  [tool.black]
57
58
  line-length = 100
@@ -0,0 +1 @@
1
+ from stdl import decorators, dt, fs, log, lst, net, st
@@ -45,7 +45,7 @@ class Timer:
45
45
  Returns:
46
46
  TimerStop: The stop data
47
47
  """
48
- t = time.time()
48
+ t = time.perf_counter()
49
49
  elapsed_total = t - self.start
50
50
  since_last = t - self.stops[-1].at if self.stops else 0
51
51
  if not self.ms:
@@ -78,7 +78,7 @@ class Timer:
78
78
 
79
79
  def reset(self) -> None:
80
80
  """Reset the timer."""
81
- self.start = time.time()
81
+ self.start = time.perf_counter()
82
82
  self.stops: list[TimerStop] = [
83
83
  TimerStop(
84
84
  total=timedelta(seconds=0),
@@ -114,17 +114,18 @@ def datetime_fmt(
114
114
  Returns:
115
115
  str: Formated date and time.
116
116
 
117
- Examples:
118
- --------
119
- >>> fmt_datetime()
120
- '2022-11-22 22:40:04' # current date and time
121
- >>> fmt_datetime(0)
122
- "1970-01-01 00:00:00"
123
- >>> fmt_datetime(0, fmt="dmY", dsep="/")
124
- "01/01/1970 00:00:00"
117
+ Example:
118
+ ```python
119
+ >>> fmt_datetime()
120
+ '2022-11-22 22:40:04' # current date and time
121
+ >>> fmt_datetime(0)
122
+ "1970-01-01 00:00:00"
123
+ >>> fmt_datetime(0, fmt="dmY", dsep="/")
124
+ "01/01/1970 00:00:00"
125
+ ```
125
126
  """
126
127
  if d is None:
127
- d = datetime.fromtimestamp(time.time(), **{"tz": timezone.utc} if utc else {})
128
+ d = datetime.fromtimestamp(time.perf_counter(), **{"tz": timezone.utc} if utc else {})
128
129
 
129
130
  elif isinstance(d, str):
130
131
  d = parse_datetime_str(d)
@@ -161,7 +162,7 @@ def time_fmt(
161
162
  str: Formated time.
162
163
  """
163
164
  if t is None:
164
- tm = datetime.fromtimestamp(time.time(), **{"tz": timezone.utc} if utc else {})
165
+ tm = datetime.fromtimestamp(time.perf_counter(), **{"tz": timezone.utc} if utc else {})
165
166
  elif isinstance(t, datetime):
166
167
  tm = t.time()
167
168
  elif isinstance(t, (int, float)):
@@ -194,19 +195,20 @@ def date_fmt(
194
195
  Returns:
195
196
  str: Formated date.
196
197
 
197
- Examples
198
- --------
199
- >>> fmt_date(date(2022,11,22))
200
- '2022-11-22'
201
- >>> fmt_date(date(2022,11,22), sep="/")
202
- '2022/11/22'
203
- >>> fmt_date(date(2022,11,22), sep="/", fmt="dmY")
204
- '22/11/2022'
205
- >>> fmt_date()
206
- '2022-11-22'
198
+ Example:
199
+ ```python
200
+ >>> fmt_date(date(2022,11,22))
201
+ '2022-11-22'
202
+ >>> fmt_date(date(2022,11,22), sep="/")
203
+ '2022/11/22'
204
+ >>> fmt_date(date(2022,11,22), sep="/", fmt="dmY")
205
+ '22/11/2022'
206
+ >>> fmt_date()
207
+ '2022-11-22'
208
+ ```
207
209
  """
208
210
  if d is None:
209
- d = date.fromtimestamp(time.time())
211
+ d = date.fromtimestamp(time.perf_counter())
210
212
  elif isinstance(d, (float, int)):
211
213
  d = date.fromtimestamp(d)
212
214
  elif isinstance(d, datetime):
@@ -222,12 +224,13 @@ def date_range(start: date, end: date) -> T.Generator[date, None, None]:
222
224
  """
223
225
  Returns a generator for dates between ``start`` and ``end``
224
226
 
225
- Examples
226
- --------
227
- >>> for i in date_range(date(2022,11,19), date(2022,11,22)): print(i)
228
- 2022-11-19
229
- 2022-11-20
230
- 2022-11-21
227
+ Example:
228
+ ```python
229
+ >>> for i in date_range(date(2022,11,19), date(2022,11,22)): print(i)
230
+ 2022-11-19
231
+ 2022-11-20
232
+ 2022-11-21
233
+ ```
231
234
  """
232
235
  for n in range(int((end - start).days)):
233
236
  yield start + timedelta(n)
@@ -102,7 +102,7 @@ class File(PathLike):
102
102
  Args:
103
103
  path (os.PathLike): File path.
104
104
  encoding (str, optional): The file's encoding.
105
- abs (bool, keyword-only): Whether to use the absolute path.
105
+ abs (bool): Whether to use the absolute path.
106
106
  """
107
107
  self.encoding = encoding
108
108
  self.path: str = os.fspath(path)
@@ -698,7 +698,9 @@ def is_wsl() -> bool:
698
698
 
699
699
 
700
700
  def mkdir(path: str | Path, mode: int = 511, exist_ok: bool = True) -> None:
701
- """Creates a directory.
701
+ """
702
+ Creates a directory.
703
+
702
704
  Args:
703
705
  path (str | Path): The path of the directory to create.
704
706
  exist_ok (bool, optional): Whether to raise an exception if the directory already exists. Defaults to True.
@@ -707,7 +709,9 @@ def mkdir(path: str | Path, mode: int = 511, exist_ok: bool = True) -> None:
707
709
 
708
710
 
709
711
  def mkdirs(dest: str | Path, names: list[str]) -> None:
710
- """Creates directories inside a destination directory.
712
+ """
713
+ Creates directories inside a destination directory.
714
+
711
715
  Args:
712
716
  dest (str | Path): The destination directory.
713
717
  names (list[str]): A list of directory names to be created in the destination directory.
@@ -863,7 +867,30 @@ def ensure_paths_exist(*args: str | PathLike | Iterable[str | PathLike]) -> None
863
867
 
864
868
  def check_path(path: str | PathLike):
865
869
  if not os.path.exists(os.fspath(path)):
866
- raise FileNotFoundError(f"Path does not exist: {path}")
870
+ raise FileNotFoundError(f"Path does not exist: '{path}'")
871
+
872
+ for path in args:
873
+ if isinstance(path, (str, bytes, PathLike)):
874
+ check_path(path)
875
+ elif isinstance(path, Iterable):
876
+ for i in path:
877
+ check_path(i)
878
+
879
+
880
+ def ensure_paths_dont_exist(*args: str | PathLike | Iterable[str | PathLike]) -> None:
881
+ """
882
+ Ensures that the specified paths don't exist.
883
+
884
+ Args:
885
+ *args : one or more strings representing the paths to check. Can also include an Iterable of paths.
886
+
887
+ Raises:
888
+ FileNotFoundError : if one of the provided paths exists.
889
+ """
890
+
891
+ def check_path(path: str | PathLike):
892
+ if os.path.exists(os.fspath(path)):
893
+ raise FileExistsError(f"Path already exists: '{path}'")
867
894
 
868
895
  for path in args:
869
896
  if isinstance(path, (str, bytes, PathLike)):
@@ -994,22 +1021,16 @@ def exec_cmd(
994
1021
  )
995
1022
 
996
1023
 
997
- def read_stdin(timeout: float = 0.0) -> list[str]:
1024
+ def read_piped() -> str:
998
1025
  """
999
- Reads lines from stdin.
1000
-
1001
- Args:
1002
- timeout (float, optional): The time to wait for input. Defaults to 0.
1003
-
1004
- Returns:
1005
- list[str]: The lines read from stdin.
1026
+ Reads piped input from stdin.
1006
1027
  """
1007
- if select([sys.stdin], [], [], timeout)[0]:
1008
- return sys.stdin.read().strip().splitlines()
1009
- return []
1028
+ if sys.stdin.isatty():
1029
+ return ""
1030
+ return sys.stdin.read().strip()
1010
1031
 
1011
1032
 
1012
- def startfile(path: str | PathLike) -> None:
1033
+ def start_file(path: str | PathLike) -> None:
1013
1034
  """
1014
1035
  Open the file with your OS's default application.
1015
1036
 
@@ -1063,8 +1084,8 @@ __all__ = [
1063
1084
  "dirname",
1064
1085
  "joinpath",
1065
1086
  "splitpath",
1066
- "read_stdin",
1067
- "startfile",
1087
+ "start_file",
1088
+ "read_piped",
1068
1089
  "isdir",
1069
1090
  "isfile",
1070
1091
  "islink",
@@ -22,13 +22,13 @@ class LoguruFormatter:
22
22
 
23
23
  def format(self, record: dict) -> str:
24
24
  """
25
- Example usage:
26
- ```python
27
- >>> import sys
28
- >>> from loguru import logger
29
- >>> logger.remove()
30
- >>> logger.add(sys.stdout, level="DEBUG", format=loguru_formater)
31
- ```
25
+ Example:
26
+ ```python
27
+ >>> import sys
28
+ >>> from loguru import logger
29
+ >>> logger.remove()
30
+ >>> logger.add(sys.stdout, level="DEBUG", format=loguru_formater)
31
+ ```
32
32
  """
33
33
  extras = ""
34
34
  if len(record["extra"]):
@@ -92,7 +92,7 @@ def occurrences(l: list[T.Any], val: T.Any) -> int:
92
92
  Returns:
93
93
  int: Number of occurrences
94
94
  """
95
- return len([i for i in l if i == val and type(i) == type(val)])
95
+ return len([i for i in l if i == val and type(i) is type(val)])
96
96
 
97
97
 
98
98
  __all__ = [
@@ -203,8 +203,10 @@ def terminal_link(
203
203
  Returns a hyperlink that can be used in terminals.
204
204
 
205
205
  NOTE:
206
- Hyperlinks are not supported in all terminals. For more information visit
207
- <https://github.com/Alhadis/OSC8-Adoption/> and
206
+ Hyperlinks are not supported in all terminals.
207
+ For more information visit
208
+ <https://github.com/Alhadis/OSC8-Adoption/>
209
+ and
208
210
  <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>
209
211
 
210
212
  Args:
@@ -234,7 +236,7 @@ def remove(s: str, chars: str | set, replace_with: str = "") -> str:
234
236
 
235
237
  Args:
236
238
  s (str): Input string.
237
- chrs (str | set): Characters to remove
239
+ chars (str | set): Characters to remove
238
240
  replace_with (str, optional): If provided, replace the characters with this value.
239
241
 
240
242
  """
@@ -255,7 +257,7 @@ def keep(s: str, chars: str | set, replace_with: str = "") -> str:
255
257
 
256
258
  Args:
257
259
  s (str): Input string
258
- chrs (str | set): Characters to keep
260
+ chars (str | set): Characters to keep
259
261
  replace_with (str, optional): If provided, replace other characters with this value.
260
262
 
261
263
  """
@@ -381,6 +383,14 @@ def ansi_rjust(s: str, width: int, fillchar: str = " ") -> str:
381
383
  return s.rjust(new_width, fillchar)
382
384
 
383
385
 
386
+ def ansi_strip(r: str) -> str:
387
+ """
388
+ Remove ANSI escape codes from a string.
389
+ """
390
+ ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
391
+ return ansi_escape.sub("", r)
392
+
393
+
384
394
  if __name__ == "__main__":
385
395
  FG.print_all()
386
396
  BG.print_all()
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stdl
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: Extended Python Standard Library
5
5
  Author-email: Žiga Ivanšek <ziga.ivansek@gmail.com>
6
6
  Project-URL: Repository, https://github.com/zigai/stdl
7
+ Project-URL: Documentation, https://stdl.readthedocs.io
7
8
  Keywords: python utilites,filesystem,string manipulation,logging configuration,list utils,standard library,ANSI colors,terminal output
8
9
  Classifier: Intended Audience :: Developers
9
10
  Classifier: License :: OSI Approved :: MIT License
@@ -1 +0,0 @@
1
- from stdl import dt, fs, log, lst, net, st
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes