feat: added annotations for init

This commit is contained in:
Hellow 2023-12-29 21:16:09 +01:00
parent 2dff8e4e0e
commit 66539e6614
7 changed files with 122 additions and 123 deletions

View File

@ -31,7 +31,7 @@ print(other_song.__dict__)
print(song) print(song)
print(type(song).__dict__["__annotations__"]) print(type(song).__dict__["__annotations__"])
""" """
"""
only_smile = Artist( only_smile = Artist(
name="Only Smile", name="Only Smile",
source_list=[Source(SourcePages.BANDCAMP, "https://onlysmile.bandcamp.com/")], source_list=[Source(SourcePages.BANDCAMP, "https://onlysmile.bandcamp.com/")],
@ -178,3 +178,4 @@ print("b: ", b)
print(c.data) print(c.data)
print(c._data) print(c._data)
"""

View File

@ -17,11 +17,13 @@ def print_lint_res(missing_values: dict):
print(f'\t"{key}": {value},') print(f'\t"{key}": {value},')
print("}") print("}")
# def __init__(self, foo: str, bar) -> None: ...
def lint_type(cls: T): def lint_type(cls: T):
all_values: dict = {}
missing_values: dict = {} missing_values: dict = {}
for key, value in cls.__dict__["__annotations__"].items(): for key, value in cls.__annotations__.items():
if value is None: if value is None:
continue continue
@ -58,6 +60,34 @@ def lint_type(cls: T):
else: else:
print(f"Everything is fine at {cls.__name__}") print(f"Everything is fine at {cls.__name__}")
p = []
s = []
for key, value in cls.__annotations__.items():
has_default = key in cls._default_factories
if not isinstance(value, str):
value = value.__name__
if key.endswith("_collection"):
key = key.replace("_collection", "_list")
if isinstance(value, str):
if value.startswith("Collection[") and value.endswith("]"):
value = value.replace("Collection", "List")
if isinstance(value, str) and has_default:
value = value + " = None"
p.append(f'{key}: {value}')
s.append(f'{key}={key}')
p.append("**kwargs")
s.append("**kwargs")
print("# This is automatically generated")
print(f"def __init__(self, {', '.join(p)}) -> None:")
print(f"\tsuper().__init__({', '.join(s)})")
print()
def lint(): def lint():
for i in ALL_CLASSES: for i in ALL_CLASSES:

View File

@ -9,12 +9,6 @@ from .country import Language
class Lyrics(OuterProxy): class Lyrics(OuterProxy):
COLLECTION_STRING_ATTRIBUTES = ("source_collection",)
SIMPLE_STRING_ATTRIBUTES = {
"text": FormattedText(),
"language": None
}
text: FormattedText text: FormattedText
language: Language language: Language
@ -26,3 +20,8 @@ class Lyrics(OuterProxy):
"source_collection": SourceCollection, "source_collection": SourceCollection,
} }
# This is automatically generated
def __init__(self, text: FormattedText = None, language: Language = None, source_list: SourceCollection = None,
**kwargs) -> None:
super().__init__(text=text, language=language, source_list=source_list, **kwargs)

View File

@ -61,43 +61,24 @@ class Song(Base):
"album_collection": Collection, "album_collection": Collection,
"feature_artist_collection": Collection, "feature_artist_collection": Collection,
"title": lambda: None,
"unified_title": lambda: None, "unified_title": lambda: None,
"isrc": lambda: None, "isrc": lambda: None,
"genre": lambda: None, "genre": lambda: None,
} }
""" def __init__(self, title: str, unified_title: str = None, isrc: str = None, length: int = None, genre: str = None,
COLLECTION_STRING_ATTRIBUTES = ( note: FormattedText = None, source_list: SourceCollection = None, target_list: List[Target] = None,
"lyrics_collection", "album_collection", "main_artist_collection", "feature_artist_collection", lyrics_list: List[Lyrics] = None, main_artist_list: List[Artist] = None,
"source_collection") feature_artist_list: List[Artist] = None, album_list: List[Album] = None, **kwargs) -> None:
SIMPLE_STRING_ATTRIBUTES = { super().__init__(title=title, unified_title=unified_title, isrc=isrc, length=length, genre=genre, note=note,
"title": None, source_list=source_list, target_list=target_list, lyrics_list=lyrics_list,
"unified_title": None, main_artist_list=main_artist_list, feature_artist_list=feature_artist_list,
"isrc": None, album_list=album_list, **kwargs)
"length": None,
"tracksort": 0,
"genre": None,
"notes": FormattedText()
}
"""
UPWARDS_COLLECTION_STRING_ATTRIBUTES = ("album_collection", "main_artist_collection", "feature_artist_collection") UPWARDS_COLLECTION_STRING_ATTRIBUTES = ("album_collection", "main_artist_collection", "feature_artist_collection")
"""
title: str = None,
unified_title: str = None,
isrc: str = None,
length: int = None,
tracksort: int = None,
genre: str = None,
source_list: List[Source] = None,
target_list: List[Target] = None,
lyrics_list: List[Lyrics] = None,
album_list: List['Album'] = None,
main_artist_list: List['Artist'] = None,
feature_artist_list: List['Artist'] = None,
notes: FormattedText = None,
"""
def __init_collections__(self) -> None: def __init_collections__(self) -> None:
self.album_collection.contain_given_in_attribute = { self.album_collection.contain_given_in_attribute = {
"artist_collection": self.main_artist_collection, "artist_collection": self.main_artist_collection,
@ -196,19 +177,6 @@ All objects dependent on Album
class Album(Base): class Album(Base):
COLLECTION_STRING_ATTRIBUTES = ("label_collection", "artist_collection", "song_collection")
SIMPLE_STRING_ATTRIBUTES = {
"title": None,
"unified_title": None,
"album_status": None,
"album_type": AlbumType.OTHER,
"language": None,
"date": ID3Timestamp(),
"barcode": None,
"albumsort": None,
"notes": FormattedText(),
}
title: str title: str
unified_title: str unified_title: str
album_status: AlbumStatus album_status: AlbumStatus
@ -225,6 +193,11 @@ class Album(Base):
label_collection: Collection[Label] label_collection: Collection[Label]
_default_factories = { _default_factories = {
"unified_title": lambda: None,
"album_status": lambda: None,
"barcode": lambda: None,
"albumsort": lambda: None,
"album_type": lambda: AlbumType.OTHER, "album_type": lambda: AlbumType.OTHER,
"language": lambda: Language.by_alpha_2("en"), "language": lambda: Language.by_alpha_2("en"),
"date": ID3Timestamp, "date": ID3Timestamp,
@ -235,13 +208,19 @@ class Album(Base):
"song_collection": Collection, "song_collection": Collection,
"label_collection": Collection, "label_collection": Collection,
"title": lambda: None,
"unified_title": lambda: None,
"album_status": lambda: None,
"barcode": lambda: None,
"albumsort": lambda: None,
} }
# This is automatically generated
def __init__(self, title: str, unified_title: str = None, album_status: AlbumStatus = None,
album_type: AlbumType = None, language: Language = None, date: ID3Timestamp = None,
barcode: str = None, albumsort: int = None, notes: FormattedText = None,
source_list: SourceCollection = None, artist_list: List[Artist] = None, song_list: List[Song] = None,
label_list: List[Label] = None, **kwargs) -> None:
super().__init__(title=title, unified_title=unified_title, album_status=album_status, album_type=album_type,
language=language, date=date, barcode=barcode, albumsort=albumsort, notes=notes,
source_list=source_list, artist_list=artist_list, song_list=song_list, label_list=label_list,
**kwargs)
DOWNWARDS_COLLECTION_STRING_ATTRIBUTES = ("song_collection", ) DOWNWARDS_COLLECTION_STRING_ATTRIBUTES = ("song_collection", )
UPWARDS_COLLECTION_STRING_ATTRIBUTES = ("artist_collection", "label_collection") UPWARDS_COLLECTION_STRING_ATTRIBUTES = ("artist_collection", "label_collection")
@ -411,6 +390,10 @@ class Artist(Base):
label_collection: Collection[Label] label_collection: Collection[Label]
_default_factories = { _default_factories = {
"unified_name": lambda: None,
"country": lambda: None,
"unformated_location": lambda: None,
"formed_in": ID3Timestamp, "formed_in": ID3Timestamp,
"notes": FormattedText, "notes": FormattedText,
"lyrical_themes": list, "lyrical_themes": list,
@ -421,13 +404,20 @@ class Artist(Base):
"main_album_collection": Collection, "main_album_collection": Collection,
"contact_collection": Collection, "contact_collection": Collection,
"label_collection": Collection, "label_collection": Collection,
"name": lambda: None,
"unified_name": lambda: None,
"country": lambda: None,
"unformated_location": lambda: None,
} }
# This is automatically generated
def __init__(self, name: str, unified_name: str = None, country: Country = None, formed_in: ID3Timestamp = None,
notes: FormattedText = None, lyrical_themes: List[str] = None, general_genre: str = None,
unformated_location: str = None, source_list: SourceCollection = None,
contact_list: List[Contact] = None, feature_song_list: List[Song] = None,
main_album_list: List[Album] = None, label_list: List[Label] = None, **kwargs) -> None:
super().__init__(name=name, unified_name=unified_name, country=country, formed_in=formed_in, notes=notes,
lyrical_themes=lyrical_themes, general_genre=general_genre,
unformated_location=unformated_location, source_list=source_list, contact_list=contact_list,
feature_song_list=feature_song_list, main_album_list=main_album_list, label_list=label_list,
**kwargs)
DOWNWARDS_COLLECTION_STRING_ATTRIBUTES = ("feature_song_collection", "main_album_collection") DOWNWARDS_COLLECTION_STRING_ATTRIBUTES = ("feature_song_collection", "main_album_collection")
UPWARDS_COLLECTION_STRING_ATTRIBUTES = ("label_collection", ) UPWARDS_COLLECTION_STRING_ATTRIBUTES = ("label_collection", )
@ -609,33 +599,15 @@ class Label(Base):
"source_collection": SourceCollection, "source_collection": SourceCollection,
"contact_collection": Collection, "contact_collection": Collection,
"name": lambda: None,
"unified_name": lambda: None, "unified_name": lambda: None,
} }
def __init__( def __init__(self, name: str, unified_name: str = None, notes: FormattedText = None,
self, source_list: SourceCollection = None, contact_list: List[Contact] = None,
_id: int = None, album_list: List[Album] = None, current_artist_list: List[Artist] = None, **kwargs) -> None:
dynamic: bool = False, super().__init__(name=name, unified_name=unified_name, notes=notes, source_list=source_list,
name: str = None, contact_list=contact_list, album_list=album_list, current_artist_list=current_artist_list,
unified_name: str = None, **kwargs)
notes: FormattedText = None,
album_list: List[Album] = None,
current_artist_list: List[Artist] = None,
source_list: List[Source] = None,
**kwargs
):
Base.__init__(self, _id=_id, dynamic=dynamic, **kwargs)
self.name: str = name
self.unified_name: str = unified_name
if unified_name is None and name is not None:
self.unified_name = unify(name)
self.notes = notes or FormattedText()
self.source_collection: SourceCollection = SourceCollection(source_list)
self.album_collection: Collection[Album] = Collection(data=album_list, element_type=Album)
self.current_artist_collection: Collection[Artist] = Collection(data=current_artist_list, element_type=Artist)
@property @property
def indexing_values(self) -> List[Tuple[str, object]]: def indexing_values(self) -> List[Tuple[str, object]]:

View File

@ -12,24 +12,25 @@ from .collection import Collection
class Source(OuterProxy): class Source(OuterProxy):
url: str
page_enum: SourcePages page_enum: SourcePages
referer_page: SourcePages referer_page: SourcePages
url: str
audio_url: str audio_url: str
_default_factories = { _default_factories = {
"page_enum": lambda: None, "audio_url": lambda: None,
"referer_page": lambda: None,
"url": str,
"audio_url": str,
} }
def __init__(self, page_enum: SourcePages, url: str, referer_page: SourcePages = None, audio_url: str = None, **kwargs) -> None: # This is automatically generated
def __init__(self, url: str, page_enum: SourcePages, referer_page: SourcePages = None, audio_url: str = None,
**kwargs) -> None:
if referer_page is None: if referer_page is None:
referer_page = page_enum referer_page = page_enum
super().__init__(page_enum=page_enum, url=url, referer_page=referer_page, audio_url=audio_url, **kwargs) super().__init__(url=url, page_enum=page_enum, referer_page=referer_page, audio_url=audio_url, **kwargs)
@classmethod @classmethod
def match_url(cls, url: str, referer_page: SourcePages) -> Optional["Source"]: def match_url(cls, url: str, referer_page: SourcePages) -> Optional["Source"]:

View File

@ -1,5 +1,7 @@
from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import List, Tuple, TextIO from typing import List, Tuple, TextIO, Union
import logging import logging
import requests import requests
@ -22,40 +24,26 @@ class Target(OuterProxy):
``` ```
""" """
file: str file_path: Path
path: str
_default_factories = { _default_factories = {
"file": str,
"path": str,
} }
SIMPLE_STRING_ATTRIBUTES = { # This is automatically generated
"_file": None, def __init__(self, file_path: Union[Path, str], relative_to_music_dir: bool = False, **kwargs) -> None:
"_path": None if not isinstance(file_path, Path):
} file_path = Path(file_path)
COLLECTION_STRING_ATTRIBUTES = tuple()
def __init__( if relative_to_music_dir:
self, file_path = Path(main_settings["music_directory"], file_path)
file: str = None,
path: str = None, super().__init__(file_path=fit_to_file_system(file_path), **kwargs)
dynamic: bool = False,
relative_to_music_dir: bool = False
) -> None:
super().__init__(dynamic=dynamic)
self._file: Path = Path(fit_to_file_system(file))
self._path: Path = fit_to_file_system(Path(main_settings["music_directory"], path) if relative_to_music_dir else Path(path))
self.is_relative_to_music_dir: bool = relative_to_music_dir self.is_relative_to_music_dir: bool = relative_to_music_dir
def __repr__(self) -> str: def __repr__(self) -> str:
return str(self.file_path) return str(self.file_path)
@property
def file_path(self) -> Path:
return Path(self._path, self._file)
@property @property
def indexing_values(self) -> List[Tuple[str, object]]: def indexing_values(self) -> List[Tuple[str, object]]:
return [('filepath', self.file_path)] return [('filepath', self.file_path)]
@ -67,8 +55,8 @@ class Target(OuterProxy):
@property @property
def size(self) -> int: def size(self) -> int:
""" """
returns the size the downloaded autio takes up in bytes returns the size the downloaded audio takes up in bytes
returns 0 if the file doesn't exsit returns 0 if the file doesn't exist
""" """
if not self.exists: if not self.exists:
return 0 return 0
@ -78,7 +66,7 @@ class Target(OuterProxy):
def create_path(self): def create_path(self):
self._path.mkdir(parents=True, exist_ok=True) self._path.mkdir(parents=True, exist_ok=True)
def copy_content(self, copy_to: "Target"): def copy_content(self, copy_to: Target):
if not self.exists: if not self.exists:
LOGGER.warning(f"No file exists at: {self.file_path}") LOGGER.warning(f"No file exists at: {self.file_path}")
return return

View File

@ -1,6 +1,14 @@
from pathlib import Path
import tomllib
data = tomllib.load(Path("/home/lars/music-kraken.conf").open("r")) class Foo:
print(data) class_attr: str
class_attr_two: str
def __init__(self, foo: str, bar) -> None: ...
f = Foo("fdfasdf", ["fsd", "fsedf"])
print(f)