diff options
| author | Max Nanis | 2026-08-18 10:59:19 -0700 |
|---|---|---|
| committer | Max Nanis | 2026-08-18 10:59:19 -0700 |
| commit | 1c4b5ed679b66591fb962ea7cee92cf46e50bd07 (patch) | |
| tree | 8fd1c79460ce9423f270f1544d3e4979482bb0ab | |
| parent | 2eab4f1b0cb7b829abd588d4690bec1e5cfaaee6 (diff) | |
| download | generalresearch-1c4b5ed679b66591fb962ea7cee92cf46e50bd07.tar.gz generalresearch-1c4b5ed679b66591fb962ea7cee92cf46e50bd07.zip | |
Ruff auto update
49 files changed, 271 insertions, 271 deletions
diff --git a/generalresearch/__init__.py b/generalresearch/__init__.py index fb5f28d..2100d41 100644 --- a/generalresearch/__init__.py +++ b/generalresearch/__init__.py @@ -37,7 +37,7 @@ def retry( try: return f(*args, **kwargs) except exceptions as e: - msg = "{}, Retrying in {} seconds...".format(e, mdelay) + msg = f"{e}, Retrying in {mdelay} seconds..." if logger: logger.warning(msg) else: diff --git a/generalresearch/currency.py b/generalresearch/currency.py index 2948d38..c76b266 100644 --- a/generalresearch/currency.py +++ b/generalresearch/currency.py @@ -44,21 +44,21 @@ class USDCent(int): def __add__(self, other): assert isinstance(other, USDCent) - res = super(USDCent, self).__add__(other) + res = super().__add__(other) return self.__class__(res) def __sub__(self, other): assert isinstance(other, USDCent) - res = super(USDCent, self).__sub__(other) + res = super().__sub__(other) return self.__class__(res) def __mul__(self, other): assert isinstance(other, USDCent) - res = super(USDCent, self).__mul__(other) + res = super().__mul__(other) return self.__class__(res) def __abs__(self): - res = super(USDCent, self).__abs__() + res = super().__abs__() return self.__class__(res) def __truediv__(self, other): @@ -85,7 +85,7 @@ class USDCent(int): return Decimal(int(self) / 100).quantize(Decimal(".01")) def to_usd_str(self) -> str: - return "${:,.2f}".format(float(self.to_usd())) + return f"${float(self.to_usd()):,.2f}" class USDMill(int): @@ -112,21 +112,21 @@ class USDMill(int): def __add__(self, other): assert isinstance(other, USDMill) - res = super(USDMill, self).__add__(other) + res = super().__add__(other) return self.__class__(res) def __sub__(self, other): assert isinstance(other, USDMill) - res = super(USDMill, self).__sub__(other) + res = super().__sub__(other) return self.__class__(res) def __mul__(self, other): assert isinstance(other, USDMill) - res = super(USDMill, self).__mul__(other) + res = super().__mul__(other) return self.__class__(res) def __abs__(self): - res = super(USDMill, self).__abs__() + res = super().__abs__() return self.__class__(res) def __truediv__(self, other): @@ -153,4 +153,4 @@ class USDMill(int): return Decimal(int(self) / 1_000).quantize(Decimal(".001")) def to_usd_str(self) -> str: - return "${:,.3f}".format(float(self.to_usd())) + return f"${float(self.to_usd()):,.3f}" diff --git a/generalresearch/incite/base.py b/generalresearch/incite/base.py index 6f1a9be..ba7d3e9 100644 --- a/generalresearch/incite/base.py +++ b/generalresearch/incite/base.py @@ -121,7 +121,7 @@ class GRLDatasets(BaseModel): assert access(path=p, mode=R_OK), f"Cannot read {p}" return self - def archive_path(self, enum_type: Union["MergeType", "DFCollectionType"]) -> Path: + def archive_path(self, enum_type: Union[MergeType, DFCollectionType]) -> Path: """ TODO: Extend this so that it takes any type of Enum and that inputs in the correct parent dir for the respective Enum @@ -135,7 +135,7 @@ class GRLDatasets(BaseModel): pjoin(self.data_src, self.incite.point, folder, str(enum_type.value)) ) - def has_data(self, enum_type: Union["MergeType", "DFCollectionType"]) -> bool: + def has_data(self, enum_type: Union[MergeType, DFCollectionType]) -> bool: path_dir = self.archive_path(enum_type=enum_type) if isdir(path_dir): return bool(listdir(path_dir)) @@ -596,7 +596,7 @@ class CollectionBase(BaseModel): first_match = True for idx, item in enumerate(self.items): - item: "DFCollectionItem" + item: DFCollectionItem # TODO: This appears to be a bug. It should be using the # IntervalRange overlaps approach - Max 2024-06-07 diff --git a/generalresearch/incite/mergers/foundations/enriched_session.py b/generalresearch/incite/mergers/foundations/enriched_session.py index 32ce7ef..a368e6c 100644 --- a/generalresearch/incite/mergers/foundations/enriched_session.py +++ b/generalresearch/incite/mergers/foundations/enriched_session.py @@ -231,7 +231,7 @@ class EnrichedSessionMerge(MergeCollection): def to_admin_response( self, - rr: "ReportRequest", + rr: ReportRequest, client: Client, product_ids: list[UUIDStr] | None = None, user: User | None = None, diff --git a/generalresearch/incite/mergers/foundations/enriched_wall.py b/generalresearch/incite/mergers/foundations/enriched_wall.py index bd77937..5a7dd2b 100644 --- a/generalresearch/incite/mergers/foundations/enriched_wall.py +++ b/generalresearch/incite/mergers/foundations/enriched_wall.py @@ -230,7 +230,7 @@ class EnrichedWallMerge(MergeCollection): def to_admin_response( self, - rr: "ReportRequest", + rr: ReportRequest, client: Client, product_ids: list[UUIDStr] | None = None, user: User | None = None, diff --git a/generalresearch/managers/gr/authentication.py b/generalresearch/managers/gr/authentication.py index 21c8793..f4185b2 100644 --- a/generalresearch/managers/gr/authentication.py +++ b/generalresearch/managers/gr/authentication.py @@ -27,7 +27,7 @@ class GRUserManager(PostgresManagerWithRedis): self, sub: str | None = None, is_superuser: bool = False, - ) -> "GRUser": + ) -> GRUser: sub = sub or f"{uuid4().hex}-{uuid4().hex}" return self.create( @@ -39,7 +39,7 @@ class GRUserManager(PostgresManagerWithRedis): self, sub: str, is_superuser: bool = False, - ) -> "GRUser": + ) -> GRUser: from generalresearch.models.gr.authentication import GRUser now = datetime.now(tz=timezone.utc) @@ -68,7 +68,7 @@ class GRUserManager(PostgresManagerWithRedis): instance.id = gr_user_id return instance - def get_by_id(self, gr_user_id: int) -> "GRUser" | None: + def get_by_id(self, gr_user_id: int) -> GRUser | None: from generalresearch.models.gr.authentication import GRUser with self.pg_config.make_connection() as conn: @@ -96,7 +96,7 @@ class GRUserManager(PostgresManagerWithRedis): assert isinstance(gr_user, GRUser), "GRUser not serialized correctly" return gr_user - def get_by_sub(self, sub: str, raises=True) -> "GRUser" | None: + def get_by_sub(self, sub: str, raises=True) -> GRUser | None: from generalresearch.models.gr.authentication import GRUser with self.pg_config.make_connection() as conn: @@ -128,10 +128,10 @@ class GRUserManager(PostgresManagerWithRedis): assert isinstance(gr_user, GRUser), "GRUser not serialized correctly" return gr_user - def get_by_sub_or_create(self, sub: str) -> "GRUser": + def get_by_sub_or_create(self, sub: str) -> GRUser: return self.get_by_sub(sub=sub, raises=False) or self.create(sub=sub) - def get_all(self) -> list["GRUser"]: + def get_all(self) -> list[GRUser]: from generalresearch.models.gr.authentication import GRUser with self.pg_config.make_connection() as conn: @@ -144,7 +144,7 @@ class GRUserManager(PostgresManagerWithRedis): return [GRUser.from_postgresql(i) for i in res] - def get_by_team(self, team_id: PositiveInt) -> list["GRUser"]: + def get_by_team(self, team_id: PositiveInt) -> list[GRUser]: from generalresearch.models.gr.authentication import GRUser with self.pg_config.make_connection() as conn: @@ -169,7 +169,7 @@ class GRUserManager(PostgresManagerWithRedis): return [GRUser.model_validate(item) for item in res] def list_product_uuids( - self, user: "GRUser", thl_pg_config: PostgresConfig + self, user: GRUser, thl_pg_config: PostgresConfig ) -> list[UUIDStr] | None: if user.business_uuids is None: LOG.warning("prefetch not run") @@ -195,7 +195,7 @@ class GRTokenManager(PostgresManager): audience: str | None = None, issuer: AnyHttpUrl | str | None = None, gr_redis_config: RedisConfig | None = None, - ) -> "GRToken": + ) -> GRToken: """Return the GRToken for this API Token. :param api_key: an api value from http header @@ -290,7 +290,7 @@ class GRTokenManager(PostgresManager): return - def get_by_user_id(self, user_id: PositiveInt) -> "GRToken" | None: + def get_by_user_id(self, user_id: PositiveInt) -> GRToken | None: # django authtoken_token table has (user_id) UNIQUE constraint # therefore, this will only return 0 or 1 GRTokens from generalresearch.models.gr.authentication import GRToken diff --git a/generalresearch/managers/gr/business.py b/generalresearch/managers/gr/business.py index 63ba474..aa440fb 100644 --- a/generalresearch/managers/gr/business.py +++ b/generalresearch/managers/gr/business.py @@ -30,7 +30,7 @@ class BusinessBankAccountManager(PostgresManager): self, business_id: PositiveInt, uuid: UUIDStr | None = None, - transfer_method: "TransferMethod" | None = None, + transfer_method: TransferMethod | None = None, account_number: str | None = None, routing_number: str | None = None, iban: str | None = None, @@ -52,12 +52,12 @@ class BusinessBankAccountManager(PostgresManager): self, business_id: PositiveInt, uuid: UUIDStr, - transfer_method: "TransferMethod", + transfer_method: TransferMethod, account_number: str | None = None, routing_number: str | None = None, iban: str | None = None, swift: str | None = None, - ) -> "BusinessBankAccount": + ) -> BusinessBankAccount: from generalresearch.models.gr.business import BusinessBankAccount ba = BusinessBankAccount.model_validate( @@ -94,7 +94,7 @@ class BusinessBankAccountManager(PostgresManager): ba.id = ba_id return ba - def get_by_business_id(self, business_id: UUIDStr) -> List["BusinessBankAccount"]: + def get_by_business_id(self, business_id: UUIDStr) -> List[BusinessBankAccount]: from generalresearch.models.gr.business import BusinessBankAccount with self.pg_config.make_connection() as conn: @@ -158,7 +158,7 @@ class BusinessAddressManager(PostgresManager): postal_code: str | None = None, phone_number: PhoneNumber | None = None, country: str | None = None, - ) -> "BusinessAddress": + ) -> BusinessAddress: from generalresearch.models.gr.business import BusinessAddress ba = BusinessAddress.model_validate( @@ -217,10 +217,10 @@ class BusinessManager(PostgresManagerWithRedis): self, uuid: UUIDStr, name: str | None = None, - team: "Team" | None = None, - kind: "BusinessType" | None = None, + team: Team | None = None, + kind: BusinessType | None = None, tax_number: str | None = None, - ) -> "Business": + ) -> Business: """ Warning: this ** does not ** update the name, team, kind, tax_number values if they differ from what was passed in for the @@ -241,10 +241,10 @@ class BusinessManager(PostgresManagerWithRedis): self, uuid: UUIDStr | None = None, name: str | None = None, - team: "Team" | None = None, - kind: "BusinessType" | None = None, + team: Team | None = None, + kind: BusinessType | None = None, tax_number: str | None = None, - ) -> "Business": + ) -> Business: from random import randint uuid = uuid or uuid4().hex @@ -258,11 +258,11 @@ class BusinessManager(PostgresManagerWithRedis): def create( self, name: str, - kind: "BusinessType" | None = None, + kind: BusinessType | None = None, uuid: UUIDStr | None = None, - team: "Team" | None = None, + team: Team | None = None, tax_number: str | None = None, - ) -> "Business": + ) -> Business: """ Behavior: does this raise on duplicate? """ @@ -304,7 +304,7 @@ class BusinessManager(PostgresManagerWithRedis): return business - def get_all(self) -> list["Business"]: + def get_all(self) -> list[Business]: """WARNING: This should be access by the /god/ page only, and only used by GRUser.is_staff as it doesn't provide any authentication on it's own. This is used because the .get_by_team_id() and @@ -338,7 +338,7 @@ class BusinessManager(PostgresManagerWithRedis): def get_by_team( self, team_id: PositiveInt, - ) -> list["Business"]: + ) -> list[Business]: # conn: psycopg.Connection = GR_POSTGRES_C.make_connection() with self.pg_config.make_connection() as conn: @@ -369,7 +369,7 @@ class BusinessManager(PostgresManagerWithRedis): def get_by_user_id( self, user_id: PositiveInt, - ) -> list["Business"]: + ) -> list[Business]: from generalresearch.models.gr.business import Business with self.pg_config.make_connection() as conn: @@ -448,7 +448,7 @@ class BusinessManager(PostgresManagerWithRedis): def get_by_uuid( self, business_uuid: UUIDStr, - ) -> "Business" | None: + ) -> Business | None: from generalresearch.models.gr.business import Business assert UUID(hex=business_uuid).hex == business_uuid @@ -476,7 +476,7 @@ class BusinessManager(PostgresManagerWithRedis): # data["contact"] = BusinessContact.model_validate(data) return Business.model_validate(data) - def get_by_id(self, business_id: PositiveInt) -> "Business" | None: + def get_by_id(self, business_id: PositiveInt) -> Business | None: from generalresearch.models.gr.business import Business assert isinstance(business_id, int) diff --git a/generalresearch/managers/gr/team.py b/generalresearch/managers/gr/team.py index d3c2561..ecb1ba4 100644 --- a/generalresearch/managers/gr/team.py +++ b/generalresearch/managers/gr/team.py @@ -33,8 +33,8 @@ class MembershipManager(PostgresManager): def create( self, - team: "Team", - gr_user: "GRUser", + team: Team, + gr_user: GRUser, privilege: MembershipPrivilege = MembershipPrivilege.READ, ) -> Membership: membership = Membership( @@ -142,7 +142,7 @@ class TeamManager(PostgresManagerWithRedis): def get_or_create( self, uuid: UUIDStr | None = None, name: str | None = None - ) -> "Team": + ) -> Team: team = self.get_by_uuid(team_uuid=uuid) @@ -151,7 +151,7 @@ class TeamManager(PostgresManagerWithRedis): return self.create(uuid=uuid, name=name or "< Unknown >") - def get_all(self) -> list["Team"]: + def get_all(self) -> list[Team]: from generalresearch.models.gr.team import Team with self.pg_config.make_connection() as conn: @@ -166,7 +166,7 @@ class TeamManager(PostgresManagerWithRedis): def create_dummy( self, uuid: UUIDStr | None = None, name: str | None = None - ) -> "Team": + ) -> Team: uuid = uuid or uuid4().hex name = name or f"name-{uuid4().hex[:12]}" @@ -176,7 +176,7 @@ class TeamManager(PostgresManagerWithRedis): self, name: str, uuid: UUIDStr | None = None, - ) -> "Team": + ) -> Team: from generalresearch.models.gr.team import Team team = Team.model_validate({"uuid": uuid or uuid4().hex, "name": name}) @@ -197,7 +197,7 @@ class TeamManager(PostgresManagerWithRedis): return team - def add_user(self, team: "Team", gr_user: "GRUser") -> "Membership": + def add_user(self, team: Team, gr_user: GRUser) -> Membership: """Create a Membership between a GRUser and a Team""" team.prefetch_gr_users(pg_config=self.pg_config, redis_config=self.redis_config) @@ -209,7 +209,7 @@ class TeamManager(PostgresManagerWithRedis): return mm.create(team=team, gr_user=gr_user) - def add_business(self, team: "Team", business: "Business") -> None: + def add_business(self, team: Team, business: Business) -> None: with self.pg_config.make_connection() as conn: with conn.cursor() as c: c.execute( @@ -225,7 +225,7 @@ class TeamManager(PostgresManagerWithRedis): ) conn.commit() - def get_by_uuid(self, team_uuid: UUIDStr) -> "Team" | None: + def get_by_uuid(self, team_uuid: UUIDStr) -> Team | None: from generalresearch.models.gr.team import Team with self.pg_config.make_connection() as conn: @@ -247,7 +247,7 @@ class TeamManager(PostgresManagerWithRedis): return Team.model_validate(res) - def get_by_id(self, team_id: PositiveInt) -> "Team" | None: + def get_by_id(self, team_id: PositiveInt) -> Team | None: from generalresearch.models.gr.team import Team with self.pg_config.make_connection() as conn: @@ -269,7 +269,7 @@ class TeamManager(PostgresManagerWithRedis): return Team.model_validate(res) - def get_by_user(self, gr_user: "GRUser") -> list["Team"]: + def get_by_user(self, gr_user: GRUser) -> list[Team]: from generalresearch.models.gr.team import Team with self.pg_config.make_connection() as conn: diff --git a/generalresearch/managers/leaderboard/manager.py b/generalresearch/managers/leaderboard/manager.py index 52312e5..0bf0312 100644 --- a/generalresearch/managers/leaderboard/manager.py +++ b/generalresearch/managers/leaderboard/manager.py @@ -189,7 +189,7 @@ class LeaderboardManager: ) self.redis_client.expire(self.key, time=self.expiration) - def hit(self, session: "Session") -> None: + def hit(self, session: Session) -> None: user = session.user match self.board_code: case LeaderboardCode.COMPLETE_COUNT: diff --git a/generalresearch/managers/thl/ipinfo.py b/generalresearch/managers/thl/ipinfo.py index d88594d..510dc63 100644 --- a/generalresearch/managers/thl/ipinfo.py +++ b/generalresearch/managers/thl/ipinfo.py @@ -178,7 +178,7 @@ class IPGeonameManager(PostgresManager): return instance - def get_by_id(self, geoname_id: PositiveInt) -> "IPGeoname": + def get_by_id(self, geoname_id: PositiveInt) -> IPGeoname: return self.fetch_geoname_ids(filter_ids=[geoname_id])[0] def fetch_geoname_ids( @@ -256,7 +256,7 @@ class IPInformationManager(PostgresManager): latitude: Decimal | None = None, longitude: Decimal | None = None, accuracy_radius: int | None = None, - ) -> "IPInformation": + ) -> IPInformation: return self.create( ip=ip or fake.ipv4_public(), geoname_id=geoname_id, @@ -338,7 +338,7 @@ class IPInformationManager(PostgresManager): latitude: Decimal | None = None, longitude: Decimal | None = None, accuracy_radius: int | None = None, - ) -> "IPInformation": + ) -> IPInformation: instance = IPInformation.model_validate( { @@ -425,7 +425,7 @@ class IPInformationManager(PostgresManager): """ self.pg_config.execute_write(query, params=data) - def get_ip_info(self, ip: IPvAnyAddressStr) -> "IPInformation" | None: + def get_ip_info(self, ip: IPvAnyAddressStr) -> IPInformation | None: res = self.fetch_ip_information(filter_ips=[ip]) if len(res) != 1: return None @@ -435,7 +435,7 @@ class IPInformationManager(PostgresManager): def fetch_ip_information( self, filter_ips: list[IPvAnyAddressStr], - ) -> list["IPInformation"]: + ) -> list[IPInformation]: if len(filter_ips) == 0: return [] @@ -456,7 +456,7 @@ class IPInformationManager(PostgresManager): self, c: Cursor, filter_ips: list[IPvAnyAddressStr], - ) -> list["IPInformation"]: + ) -> list[IPInformation]: """ IPs are converted to normalized form (/64 network exploded) for DB lookup, and are then matched back to the original queried form for return. diff --git a/generalresearch/managers/thl/ledger_manager/conditions.py b/generalresearch/managers/thl/ledger_manager/conditions.py index fc56550..a457f30 100644 --- a/generalresearch/managers/thl/ledger_manager/conditions.py +++ b/generalresearch/managers/thl/ledger_manager/conditions.py @@ -24,14 +24,14 @@ if TYPE_CHECKING: ) -def generate_condition_mp_payment(wall: "Wall") -> Callable[..., bool]: +def generate_condition_mp_payment(wall: Wall) -> Callable[..., bool]: """This returns a function that checks if the payment for this wall event exists already. This function gets run after we acquire a lock. It should return True if we want to continue (create a tx). """ wall_uuid = wall.uuid - def _condition(lm: "LedgerManager") -> bool: + def _condition(lm: LedgerManager) -> bool: tag = f"{lm.currency.value}:mp_payment:{wall_uuid}" txs = lm.get_tx_ids_by_tag(tag=tag) return len(txs) == 0 @@ -39,14 +39,14 @@ def generate_condition_mp_payment(wall: "Wall") -> Callable[..., bool]: return _condition -def generate_condition_bp_payment(session: "Session") -> Callable[..., bool]: +def generate_condition_bp_payment(session: Session) -> Callable[..., bool]: """This returns a function that checks if the payment for this Session exists already. This function gets run after we acquire a lock. It should return True if we want to continue (create a tx). """ session_uuid = session.uuid - def _condition(lm: "LedgerManager") -> bool: + def _condition(lm: LedgerManager) -> bool: tag = f"{lm.currency.value}:bp_payment:{session_uuid}" txs_ids = lm.get_tx_ids_by_tag(tag=tag) return len(txs_ids) == 0 @@ -59,7 +59,7 @@ def generate_condition_tag_exists(tag: str) -> Callable[..., bool]: exists. It should return True if we want to continue (create a tx). """ - def _condition(lm: "LedgerManager") -> bool: + def _condition(lm: LedgerManager) -> bool: txs_ids = lm.get_tx_ids_by_tag(tag=tag) return len(txs_ids) == 0 @@ -67,7 +67,7 @@ def generate_condition_tag_exists(tag: str) -> Callable[..., bool]: def generate_condition_bp_payout( - product: "Product", + product: Product, amount: USDCent, payoutevent_uuid: UUIDStr, skip_one_per_day_check: bool = False, @@ -76,7 +76,7 @@ def generate_condition_bp_payout( created = datetime.now(tz=timezone.utc) def _condition( - lm: "ThlLedgerManager", + lm: ThlLedgerManager, ) -> tuple[bool, str]: bp_wallet_account = lm.get_account_or_create_bp_wallet(product=product) tag = f"{lm.currency.value}:bp_payout:{payoutevent_uuid}" @@ -124,7 +124,7 @@ def generate_condition_user_payout_request( if min_balance is not None: assert isinstance(min_balance, int) - def _condition(lm: "ThlLedgerManager") -> bool: + def _condition(lm: ThlLedgerManager) -> bool: tag = f"{lm.currency.value}:user_payout:{payoutevent_uuid}:request" txs_ids = lm.get_tx_ids_by_tag(tag) @@ -159,7 +159,7 @@ def generate_condition_enter_contest( """ assert isinstance(min_balance, USDCent), "balance must be USDCent" - def _condition(lm: "ThlLedgerManager") -> tuple[bool, str]: + def _condition(lm: ThlLedgerManager) -> tuple[bool, str]: txs_ids = lm.get_tx_ids_by_tag(tag) if len(txs_ids) != 0: logger.info(f"{tag} failed condition check duplicate transaction") @@ -190,7 +190,7 @@ def generate_condition_user_payout_action( :param action: should be in {'complete', 'cancel'} """ - def _condition(lm: "ThlLedgerManager") -> bool: + def _condition(lm: ThlLedgerManager) -> bool: tag = f"{lm.currency.value}:user_payout:{payoutevent_uuid}:{action}" txs_ids = lm.get_tx_ids_by_tag(tag) if len(txs_ids) != 0: diff --git a/generalresearch/managers/thl/ledger_manager/thl_ledger.py b/generalresearch/managers/thl/ledger_manager/thl_ledger.py index dcdfcf3..2fd0a2a 100644 --- a/generalresearch/managers/thl/ledger_manager/thl_ledger.py +++ b/generalresearch/managers/thl/ledger_manager/thl_ledger.py @@ -181,15 +181,15 @@ class ThlLedgerManager(LedgerManager): def get_account_or_create_contest_wallet( self, contest: RaffleContest - ) -> "LedgerAccount": + ) -> LedgerAccount: assert isinstance(contest, RaffleContest), "Must provide a RaffleContest" return self.get_account_or_create_contest_wallet_by_uuid( contest_uuid=contest.uuid ) def get_or_create_bp_pending_payout_account( - self, product: "Product" - ) -> "LedgerAccount": + self, product: Product + ) -> LedgerAccount: """ Used exclusively for BP with managed user wallets. This account holds funds that a BP's users have requested as payouts but are @@ -211,7 +211,7 @@ class ThlLedgerManager(LedgerManager): return self.get_account_or_create(account=account) - def get_account_task_complete_revenue(self) -> "LedgerAccount": + def get_account_task_complete_revenue(self) -> LedgerAccount: res = self.get_account( qualified_name=f"{self.currency.value}:revenue:task_complete" ) @@ -219,7 +219,7 @@ class ThlLedgerManager(LedgerManager): return res - def get_account_cash(self) -> "LedgerAccount": + def get_account_cash(self) -> LedgerAccount: res = self.get_account(qualified_name=f"{self.currency.value}:cash") assert res is not None, "Cash account does not exist" @@ -1719,7 +1719,7 @@ class ThlLedgerManager(LedgerManager): def create_tx_milestone_winner( self, contest: MilestoneContest, - winners: list["ContestWinner"], + winners: list[ContestWinner], skip_flag_check: bool | None = False, ) -> LedgerTransaction: """ diff --git a/generalresearch/managers/thl/payout.py b/generalresearch/managers/thl/payout.py index 43f7dc1..d7174f3 100644 --- a/generalresearch/managers/thl/payout.py +++ b/generalresearch/managers/thl/payout.py @@ -653,7 +653,7 @@ class BrokerageProductPayoutEventManager(PayoutEventManager): thl_ledger_manager: ThlLedgerManager, product_uuids: Collection[UUIDStr], order_by: OrderBy | None = OrderBy.ASC, - ) -> list["BrokerageProductPayoutEvent"]: + ) -> list[BrokerageProductPayoutEvent]: """This is a terrible name, but it returns the BPPayoutEvent model type rather than a list of PayoutEvents. @@ -988,7 +988,7 @@ class BusinessPayoutEventManager(BrokerageProductPayoutEventManager): thl_ledger_manager: ThlLedgerManager, product_uuids: Collection[UUIDStr], order_by: OrderBy | None = OrderBy.ASC, - ) -> list["BusinessPayoutEvent"]: + ) -> list[BusinessPayoutEvent]: res = self.get_bp_bp_payout_events_for_products( thl_ledger_manager=thl_ledger_manager, product_uuids=product_uuids, @@ -999,8 +999,8 @@ class BusinessPayoutEventManager(BrokerageProductPayoutEventManager): @staticmethod def from_bp_payout_events( - bp_payout_events: Collection["BrokerageProductPayoutEvent"], - ) -> list["BusinessPayoutEvent"]: + bp_payout_events: Collection[BrokerageProductPayoutEvent], + ) -> list[BusinessPayoutEvent]: if len(bp_payout_events) == 0: return [] diff --git a/generalresearch/managers/thl/product.py b/generalresearch/managers/thl/product.py index 36e8fc7..00bf032 100644 --- a/generalresearch/managers/thl/product.py +++ b/generalresearch/managers/thl/product.py @@ -62,7 +62,7 @@ class ProductManager(PostgresManager): def get_by_uuid( self, product_uuid: UUIDStr, - ) -> "Product": + ) -> Product: assert is_valid_uuid(product_uuid), "invalid uuid" res = self.fetch_uuids( product_uuids=[product_uuid], @@ -74,7 +74,7 @@ class ProductManager(PostgresManager): def get_by_uuids( self, product_uuids: list[UUIDStr], - ) -> list["Product"]: + ) -> list[Product]: res = self.fetch_uuids( product_uuids=product_uuids, @@ -88,7 +88,7 @@ class ProductManager(PostgresManager): def get_by_uuid_if_exists( self, product_uuid: UUIDStr, - ) -> "Product" | None: + ) -> Product | None: # many=False, raise_on_error=False try: return self.fetch_uuids( @@ -102,13 +102,13 @@ class ProductManager(PostgresManager): def get_by_uuids_if_exists( self, product_uuids: list[UUIDStr], - ) -> list["Product"]: + ) -> list[Product]: # Same as .get_by_uuids but doesn't raise Exception if len(product_uuids) != len(res) return self.fetch_uuids( product_uuids=product_uuids, ) - def get_all(self, rand_limit: int | None) -> list["Product"]: + def get_all(self, rand_limit: int | None) -> list[Product]: product_uuids = self.get_all_uuids(rand_limit=rand_limit) return self.fetch_uuids(product_uuids=product_uuids) @@ -137,7 +137,7 @@ class ProductManager(PostgresManager): product_uuids: list[UUIDStr] | None = None, business_uuids: list[UUIDStr] | None = None, team_uuids: list[UUIDStr] | None = None, - ) -> list["Product"]: + ) -> list[Product]: LOG.debug(f"PM.fetch_uuids({product_uuids=}, {business_uuids=}, {team_uuids=})") assert ( @@ -181,7 +181,7 @@ class ProductManager(PostgresManager): def fetch_uuids_( self, c: Cursor, filter_uuids: list[UUIDStr], filter_column: str - ) -> list["Product"]: + ) -> list[Product]: from generalresearch.models.thl.product import Product assert len(filter_uuids) <= 500, "chunk me" @@ -273,14 +273,14 @@ class ProductManager(PostgresManager): redirect_url: str | None = None, harmonizer_domain: str | None = None, commission_pct: Decimal = Decimal("0.05000"), - sources_config: "SourcesConfig" | "SupplyConfigs" | None = None, - payout_config: "PayoutConfig" | None = None, - session_config: "SessionConfig" | None = None, - profiling_config: "ProfilingConfig" | None = None, - user_wallet_config: "UserWalletConfig" | None = None, - user_create_config: "UserCreateConfig" | None = None, - user_health_config: "UserHealthConfig" | None = None, - ) -> "Product": + sources_config: SourcesConfig | SupplyConfigs | None = None, + payout_config: PayoutConfig | None = None, + session_config: SessionConfig | None = None, + profiling_config: ProfilingConfig | None = None, + user_wallet_config: UserWalletConfig | None = None, + user_create_config: UserCreateConfig | None = None, + user_health_config: UserHealthConfig | None = None, + ) -> Product: """To be used in tests, where we don't care about certain fields""" product_id = product_id if product_id else uuid4().hex team_id = team_id if team_id else uuid4().hex @@ -313,14 +313,14 @@ class ProductManager(PostgresManager): business_id: UUIDStr | None = None, harmonizer_domain: str | None = None, commission_pct: Decimal = Decimal("0.05"), - sources_config: "SourcesConfig" | "SupplyConfigs" | None = None, - payout_config: "PayoutConfig" | None = None, - session_config: "SessionConfig" | None = None, - profiling_config: "ProfilingConfig" | None = None, - user_wallet_config: "UserWalletConfig" | None = None, - user_create_config: "UserCreateConfig" | None = None, - user_health_config: "UserHealthConfig" | None = None, - ) -> "Product": + sources_config: SourcesConfig | SupplyConfigs | None = None, + payout_config: PayoutConfig | None = None, + session_config: SessionConfig | None = None, + profiling_config: ProfilingConfig | None = None, + user_wallet_config: UserWalletConfig | None = None, + user_create_config: UserCreateConfig | None = None, + user_health_config: UserHealthConfig | None = None, + ) -> Product: """Create a Product with all the basic defaults and return the instance""" from generalresearch.models.thl.product import ( PayoutConfig, @@ -474,7 +474,7 @@ class ProductManager(PostgresManager): return instance - def update(self, new_product: "Product") -> None: + def update(self, new_product: Product) -> None: product_uuid = new_product.id old_product = self.get_by_uuid(product_uuid=product_uuid) old_dump = old_product.model_dump(mode="json") diff --git a/generalresearch/models/__init__.py b/generalresearch/models/__init__.py index 0a013e2..9a2bb9c 100644 --- a/generalresearch/models/__init__.py +++ b/generalresearch/models/__init__.py @@ -85,7 +85,7 @@ class TaskCalculationType(str, Enum): STARTS = "STARTS" @classmethod - def from_api(cls, v: str) -> "TaskCalculationType": + def from_api(cls, v: str) -> TaskCalculationType: return { "complete": cls.COMPLETES, "completes": cls.COMPLETES, @@ -97,11 +97,11 @@ class TaskCalculationType(str, Enum): }[v.lower()] @classmethod - def prodege_from_api(cls, v: int) -> "TaskCalculationType": + def prodege_from_api(cls, v: int) -> TaskCalculationType: return {1: cls.COMPLETES, 2: cls.STARTS}[v] @classmethod - def innovate_from_api(cls, v: int) -> "TaskCalculationType": + def innovate_from_api(cls, v: int) -> TaskCalculationType: return {0: cls.COMPLETES, 1: cls.STARTS}[v] diff --git a/generalresearch/models/cint/question.py b/generalresearch/models/cint/question.py index b870246..1ac9eea 100644 --- a/generalresearch/models/cint/question.py +++ b/generalresearch/models/cint/question.py @@ -213,7 +213,7 @@ class CintQuestion(MarketplaceQuestion): return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/dynata/survey.py b/generalresearch/models/dynata/survey.py index d65b55d..0e1b3e5 100644 --- a/generalresearch/models/dynata/survey.py +++ b/generalresearch/models/dynata/survey.py @@ -98,7 +98,7 @@ class DynataCondition(MarketplaceCondition): tag: str | None = Field(default=None, max_length=36) @classmethod - def from_api(cls, cell: dict[str, Any]) -> "DynataCondition": + def from_api(cls, cell: dict[str, Any]) -> DynataCondition: """ We perform some preprocessing before calling this to pull in the data from COLLECTION cells. """ diff --git a/generalresearch/models/gr/authentication.py b/generalresearch/models/gr/authentication.py index 8b09e7e..4ee70f9 100644 --- a/generalresearch/models/gr/authentication.py +++ b/generalresearch/models/gr/authentication.py @@ -112,11 +112,11 @@ class GRUser(BaseModel): ) # prefetch attributes - businesses: list["Business"] | None = Field(default=None) - teams: list["Team"] | None = Field(default=None) - products: list["Product"] | None = Field(default=None) - token: "GRToken | None" = Field(default=None) - claims: "Claims | None" = Field(default=None) + businesses: list[Business] | None = Field(default=None) + teams: list[Team] | None = Field(default=None) + products: list[Product] | None = Field(default=None) + token: GRToken | None = Field(default=None) + claims: Claims | None = Field(default=None) def prefetch_claims( self, token: str, key: dict[str, Any], audience: str, issuer: AnyHttpUrl @@ -192,7 +192,7 @@ class GRUser(BaseModel): tm = GRTokenManager(pg_config=pg_config) self.token = tm.get_by_user_id(user_id=self.id) - def __eq__(self, other: "GRUser") -> bool: + def __eq__(self, other: GRUser) -> bool: return self.id == other.id # --- Validations --- @@ -327,7 +327,7 @@ class GRToken(BaseModel): user_id: PositiveInt = Field() # --- prefetch field --- - user: "GRUser | None" = Field(default=None) + user: GRUser | None = Field(default=None) @property def sso(self) -> bool: @@ -348,7 +348,7 @@ class GRToken(BaseModel): self.user = gr_um.get_by_id(gr_user_id=self.user_id) - def __eq__(self, other: "GRToken") -> bool: + def __eq__(self, other: GRToken) -> bool: return self.key == other.key @field_validator("created", mode="before") diff --git a/generalresearch/models/gr/business.py b/generalresearch/models/gr/business.py index 4455ff0..c5af8d6 100644 --- a/generalresearch/models/gr/business.py +++ b/generalresearch/models/gr/business.py @@ -84,7 +84,7 @@ class BusinessBankAccount(BaseModel): # 'business' is a Class with values that are fetched from the DB. # Initialization is deferred until it is actually needed # (see .prefetch_business()) - business: SkipJsonSchema["Business | None"] = Field(default=None) + business: SkipJsonSchema[Business | None] = Field(default=None) transfer_method: TransferMethod = Field( description=TransferMethod.as_openapi(), @@ -194,18 +194,18 @@ class Business(BaseModel): ) tax_number: str | None = Field(default=None, max_length=20) - contact: "BusinessContact | None" = Field(default=None) + contact: BusinessContact | None = Field(default=None) # Initialization is deferred until it is actually needed # (see .prefetch_***()) - addresses: list["BusinessAddress"] | None = Field(default=None) - teams: list["Team"] | None = Field(default=None) - products: list["Product"] | None = Field(default=None) - bank_accounts: list["BusinessBankAccount"] | None = Field(default=None) + addresses: list[BusinessAddress] | None = Field(default=None) + teams: list[Team] | None = Field(default=None) + products: list[Product] | None = Field(default=None) + bank_accounts: list[BusinessBankAccount] | None = Field(default=None) # Initialization is deferred until unless it's called # (see .prebuild_***()) - balance: "BusinessBalances | None" = Field(default=None, name="Business Balance") + balance: BusinessBalances | None = Field(default=None, name="Business Balance") payouts_total_str: str | None = Field(default=None) payouts_total: USDCent | None = Field(default=None) @@ -343,10 +343,10 @@ class Business(BaseModel): def prebuild_balance( self, thl_pg_config: PostgresConfig, - lm: "LedgerManager", - ds: "GRLDatasets", + lm: LedgerManager, + ds: GRLDatasets, client: Client, - pop_ledger: "PopLedgerMerge | None" = None, + pop_ledger: PopLedgerMerge | None = None, at_timestamp: AwareDatetime | None = None, ) -> None: """ @@ -438,7 +438,7 @@ class Business(BaseModel): def prebuild_payouts( self, thl_pg_config: PostgresConfig, - thl_lm: "ThlLedgerManager", + thl_lm: ThlLedgerManager, bpem: BusinessPayoutEventManager, ) -> None: LOG.debug(f"Business.prebuild_payouts({self.uuid=})") @@ -463,10 +463,10 @@ class Business(BaseModel): def prebuild_pop_financial( self, thl_pg_config: PostgresConfig, - thl_lm: "ThlLedgerManager", - ds: "GRLDatasets", + thl_lm: ThlLedgerManager, + ds: GRLDatasets, client: Client, - pop_ledger: "PopLedgerMerge | None" = None, + pop_ledger: PopLedgerMerge | None = None, ) -> None: """This is very similar to the Product POP Financial endpoint; however, it returns more than one item for a single time interval. This is @@ -518,10 +518,10 @@ class Business(BaseModel): def prebuild_enriched_session_parquet( self, thl_pg_config: PostgresConfig, - ds: "GRLDatasets", + ds: GRLDatasets, client: Client, mnt_gr_api: Path, - enriched_session: "EnrichedSessionMerge | None" = None, + enriched_session: EnrichedSessionMerge | None = None, ) -> None: self.prefetch_products(thl_pg_config=thl_pg_config) @@ -556,17 +556,17 @@ class Business(BaseModel): try: test = pd.read_parquet(path, engine="pyarrow") except Exception as e: - raise IOError(f"Parquet verification failed: {e}") + raise OSError(f"Parquet verification failed: {e}") return None def prebuild_enriched_wall_parquet( self, thl_pg_config: PostgresConfig, - ds: "GRLDatasets", + ds: GRLDatasets, client: Client, mnt_gr_api: Path, - enriched_wall: "EnrichedWallMerge | None" = None, + enriched_wall: EnrichedWallMerge | None = None, ) -> None: self.prefetch_products(thl_pg_config=thl_pg_config) @@ -601,7 +601,7 @@ class Business(BaseModel): try: test = pd.read_parquet(path, engine="pyarrow") except Exception as e: - raise IOError(f"Parquet verification failed: {e}") + raise OSError(f"Parquet verification failed: {e}") return None @@ -638,15 +638,15 @@ class Business(BaseModel): pg_config: PostgresConfig, thl_web_rr: PostgresConfig, redis_config: RedisConfig, - client: "Client", - ds: "GRLDatasets", - lm: "LedgerManager", - thl_lm: "ThlLedgerManager", - bpem: "BusinessPayoutEventManager", + client: Client, + ds: GRLDatasets, + lm: LedgerManager, + thl_lm: ThlLedgerManager, + bpem: BusinessPayoutEventManager, mnt_gr_api: Path | str, - pop_ledger: "PopLedgerMerge | None" = None, - enriched_session: "EnrichedSessionMerge | None" = None, - enriched_wall: "EnrichedWallMerge | None" = None, + pop_ledger: PopLedgerMerge | None = None, + enriched_session: EnrichedSessionMerge | None = None, + enriched_wall: EnrichedWallMerge | None = None, ) -> None: LOG.debug(f"Business.set_cache({self.uuid=})") diff --git a/generalresearch/models/gr/team.py b/generalresearch/models/gr/team.py index 4a18875..8d60825 100644 --- a/generalresearch/models/gr/team.py +++ b/generalresearch/models/gr/team.py @@ -84,7 +84,7 @@ class Membership(BaseModel): team_id: SkipJsonSchema[PositiveInt] = Field() # prefetch attributes - team: SkipJsonSchema["Team | None"] = Field(default=None) + team: SkipJsonSchema[Team | None] = Field(default=None) # --- Validators --- @@ -112,10 +112,10 @@ class Team(BaseModel): name: str = Field(max_length=255, examples=["Team ABC"]) # prefetch attributes - memberships: SkipJsonSchema[list["Membership"] | None] = Field(default=None) - gr_users: SkipJsonSchema[list["GRUser"] | None] = Field(default=None) - businesses: SkipJsonSchema[list["Business"] | None] = Field(default=None) - products: SkipJsonSchema[list["Product"] | None] = Field(default=None) + memberships: SkipJsonSchema[list[Membership] | None] = Field(default=None) + gr_users: SkipJsonSchema[list[GRUser] | None] = Field(default=None) + businesses: SkipJsonSchema[list[Business] | None] = Field(default=None) + products: SkipJsonSchema[list[Product] | None] = Field(default=None) # --- Prefetch Methods --- @@ -155,10 +155,10 @@ class Team(BaseModel): def prebuild_enriched_session_parquet( self, thl_pg_config: PostgresConfig, - ds: "GRLDatasets", + ds: GRLDatasets, client: Client, mnt_gr_api: Path, - enriched_session: "EnrichedSessionMerge | None" = None, + enriched_session: EnrichedSessionMerge | None = None, ) -> None: self.prefetch_products(thl_pg_config=thl_pg_config) @@ -193,17 +193,17 @@ class Team(BaseModel): try: _ = pd.read_parquet(path, engine="pyarrow") except Exception as e: - raise IOError(f"Parquet verification failed: {e}") + raise OSError(f"Parquet verification failed: {e}") return def prebuild_enriched_wall_parquet( self, thl_pg_config: PostgresConfig, - ds: "GRLDatasets", + ds: GRLDatasets, client: Client, mnt_gr_api: Path, - enriched_wall: "EnrichedWallMerge | None" = None, + enriched_wall: EnrichedWallMerge | None = None, ) -> None: self.prefetch_products(thl_pg_config=thl_pg_config) @@ -238,7 +238,7 @@ class Team(BaseModel): try: _ = pd.read_parquet(path, engine="pyarrow") except Exception as e: - raise IOError(f"Parquet verification failed: {e}") + raise OSError(f"Parquet verification failed: {e}") return None @@ -278,11 +278,11 @@ class Team(BaseModel): pg_config: PostgresConfig, thl_web_rr: PostgresConfig, redis_config: RedisConfig, - client: "Client", - ds: "GRLDatasets", + client: Client, + ds: GRLDatasets, mnt_gr_api: Path | str, - enriched_session: "EnrichedSessionMerge | None" = None, - enriched_wall: "EnrichedWallMerge | None" = None, + enriched_session: EnrichedSessionMerge | None = None, + enriched_wall: EnrichedWallMerge | None = None, ) -> None: ex_secs = 60 * 60 * 24 * 3 # 3 days diff --git a/generalresearch/models/innovate/question.py b/generalresearch/models/innovate/question.py index d385b42..306274f 100644 --- a/generalresearch/models/innovate/question.py +++ b/generalresearch/models/innovate/question.py @@ -142,7 +142,7 @@ class InnovateQuestion(MarketplaceQuestion): @classmethod def from_api( cls, d: dict, country_iso: str, language_iso: str - ) -> "InnovateQuestion | None": + ) -> InnovateQuestion | None: """ :param d: Raw response from API :param country_iso: @@ -158,7 +158,7 @@ class InnovateQuestion(MarketplaceQuestion): @classmethod def _from_api( cls, d: dict, country_iso: str, language_iso: str - ) -> "InnovateQuestion": + ) -> InnovateQuestion: # Question AGE returns options even though its marked as a text entry (but only in some locales) d["QuestionKey"] = d["QuestionKey"].lower() if d["QuestionKey"] == "age": @@ -185,7 +185,7 @@ class InnovateQuestion(MarketplaceQuestion): ) @classmethod - def from_db(cls, d: dict[str, Any]) -> "InnovateQuestion": + def from_db(cls, d: dict[str, Any]) -> InnovateQuestion: options = None if d["options"]: @@ -212,7 +212,7 @@ class InnovateQuestion(MarketplaceQuestion): d["options"] = json.dumps(d["options"]) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/innovate/survey.py b/generalresearch/models/innovate/survey.py index 985947e..bcd50d3 100644 --- a/generalresearch/models/innovate/survey.py +++ b/generalresearch/models/innovate/survey.py @@ -66,7 +66,7 @@ class InnovateCondition(MarketplaceCondition): values: list[Annotated[str, Field(max_length=128)]] = Field() @classmethod - def from_api(cls, d: dict[str, Any]) -> "InnovateCondition": + def from_api(cls, d: dict[str, Any]) -> InnovateCondition: d["logical_operator"] = LogicalOperator.OR d["value_type"] = ConditionValueType.LIST d["negate"] = False @@ -261,7 +261,7 @@ class InnovateSurvey(MarketplaceTask): return data @classmethod - def from_api(cls, d: dict[str, Any]) -> "InnovateSurvey | None": + def from_api(cls, d: dict[str, Any]) -> InnovateSurvey | None: try: return cls._from_api(d) except Exception as e: @@ -269,7 +269,7 @@ class InnovateSurvey(MarketplaceTask): return None @classmethod - def _from_api(cls, d: dict[str, Any]) -> "InnovateSurvey": + def _from_api(cls, d: dict[str, Any]) -> InnovateSurvey: d["conditions"] = dict() # If we haven't hit the "detail" endpoint, we won't get this @@ -329,7 +329,7 @@ class InnovateSurvey(MarketplaceTask): ) return f"{self.__repr_name__()}({repr_str})" - def is_unchanged(self, other: "InnovateSurvey") -> bool: + def is_unchanged(self, other: InnovateSurvey) -> bool: # Avoiding overloading __eq__ because it looks kind of complicated? I # want to be explicit that this is not testing object equivalence, # just that the objects don't require any db updates. We also exclude diff --git a/generalresearch/models/legacy/bucket.py b/generalresearch/models/legacy/bucket.py index 52cbacf..2650b0b 100644 --- a/generalresearch/models/legacy/bucket.py +++ b/generalresearch/models/legacy/bucket.py @@ -439,7 +439,7 @@ class DurationSummary(StatisticalSummary): } @classmethod - def from_bucket(cls, bucket: Bucket) -> "DurationSummary": + def from_bucket(cls, bucket: Bucket) -> DurationSummary: return cls( min=bucket.loi_min.total_seconds(), max=bucket.loi_max.total_seconds(), @@ -624,7 +624,7 @@ class TopNPlusBucket(BucketBase): return tuple(sorted(criteria, key=lambda c: c.rank)) @classmethod - def from_bucket(cls, bucket: Bucket) -> "TopNPlusBucket": + def from_bucket(cls, bucket: Bucket) -> TopNPlusBucket: return cls.model_validate( { "id": bucket.id, diff --git a/generalresearch/models/legacy/offerwall.py b/generalresearch/models/legacy/offerwall.py index 0e54387..da28663 100644 --- a/generalresearch/models/legacy/offerwall.py +++ b/generalresearch/models/legacy/offerwall.py @@ -203,7 +203,7 @@ class SoftPairOfferwall(OfferWall): buckets: list[SoftPairBucket] = Field(default_factory=list) - question_info: dict[str, "UpkQuestion"] = Field( + question_info: dict[str, UpkQuestion] = Field( default_factory=dict, examples=[ # { diff --git a/generalresearch/models/legacy/questions.py b/generalresearch/models/legacy/questions.py index 04891ae..81e794c 100644 --- a/generalresearch/models/legacy/questions.py +++ b/generalresearch/models/legacy/questions.py @@ -217,7 +217,7 @@ class UserQuestionAnswers(BaseModel): return v # --- Prefetch --- - def prefetch_user(self, um: "UserManager") -> None: + def prefetch_user(self, um: UserManager) -> None: from generalresearch.models.thl.user import User res: User | None = um.get_user_if_exists( @@ -229,7 +229,7 @@ class UserQuestionAnswers(BaseModel): self.user = res - def prefetch_wall(self, wm: "WallManager") -> None: + def prefetch_wall(self, wm: WallManager) -> None: from generalresearch.models import Source from generalresearch.models.thl.session import Wall diff --git a/generalresearch/models/lucid/question.py b/generalresearch/models/lucid/question.py index 01c7859..908ce70 100644 --- a/generalresearch/models/lucid/question.py +++ b/generalresearch/models/lucid/question.py @@ -110,7 +110,7 @@ class LucidQuestion(MarketplaceQuestion): options=options, ) - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/network/nmap/parser.py b/generalresearch/models/network/nmap/parser.py index 49c13c7..967f208 100644 --- a/generalresearch/models/network/nmap/parser.py +++ b/generalresearch/models/network/nmap/parser.py @@ -1,6 +1,6 @@ from __future__ import annotations -import xml.etree.cElementTree as ET +import xml.etree.ElementTree as ET from datetime import datetime, timezone from typing import Any @@ -49,7 +49,7 @@ class NmapXmlParser: try: root = ET.fromstring(nmap_data) except Exception as e: - emsg = "Wrong XML structure: cannot parse data: {0}".format(e) + emsg = f"Wrong XML structure: cannot parse data: {e}" raise NmapParserException(emsg) if root.tag != "nmaprun": diff --git a/generalresearch/models/pollfish/question.py b/generalresearch/models/pollfish/question.py index 9508154..ae0dc5a 100644 --- a/generalresearch/models/pollfish/question.py +++ b/generalresearch/models/pollfish/question.py @@ -104,7 +104,7 @@ class PollfishQuestion(MarketplaceQuestion): d["options"] = json.dumps(d["options"]) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/precision/question.py b/generalresearch/models/precision/question.py index e74a46a..4030509 100644 --- a/generalresearch/models/precision/question.py +++ b/generalresearch/models/precision/question.py @@ -106,7 +106,7 @@ class PrecisionQuestion(MarketplaceQuestion): return self @classmethod - def from_api(cls, d: dict[str, Any]) -> "PrecisionQuestion | None": + def from_api(cls, d: dict[str, Any]) -> PrecisionQuestion | None: """ :param d: Raw response from API """ @@ -117,7 +117,7 @@ class PrecisionQuestion(MarketplaceQuestion): return None @classmethod - def _from_api(cls, d: dict[str, Any]) -> "PrecisionQuestion": + def _from_api(cls, d: dict[str, Any]) -> PrecisionQuestion: question_type = PrecisionQuestionType.from_api(d["question_type_name"]) # sometimes an empty option is returned .... ? options = [ @@ -139,7 +139,7 @@ class PrecisionQuestion(MarketplaceQuestion): ) @classmethod - def from_db(cls, d: dict[str, Any]) -> "PrecisionQuestion": + def from_db(cls, d: dict[str, Any]) -> PrecisionQuestion: options = None if d["options"]: options = [ @@ -163,7 +163,7 @@ class PrecisionQuestion(MarketplaceQuestion): d["options"] = json.dumps(d["options"]) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/prodege/question.py b/generalresearch/models/prodege/question.py index f1f9230..1c61ab9 100644 --- a/generalresearch/models/prodege/question.py +++ b/generalresearch/models/prodege/question.py @@ -139,7 +139,7 @@ class ProdegeQuestion(MarketplaceQuestion): return self @classmethod - def from_api(cls, d: dict[str, Any], country_iso: str) -> "ProdegeQuestion | None": + def from_api(cls, d: dict[str, Any], country_iso: str) -> ProdegeQuestion | None: """ :param d: Raw response from API """ @@ -150,7 +150,7 @@ class ProdegeQuestion(MarketplaceQuestion): return None @classmethod - def _from_api(cls, d: dict[str, Any], country_iso: str) -> "ProdegeQuestion": + def _from_api(cls, d: dict[str, Any], country_iso: str) -> ProdegeQuestion: # The API has no concept of language at all. Questions for a country # are returned both in english and other languages. Questions do have # a field 'country_specific', and if True, that generally means the @@ -183,7 +183,7 @@ class ProdegeQuestion(MarketplaceQuestion): return cls.model_validate(d) @classmethod - def from_db(cls, d: dict[str, Any]) -> "ProdegeQuestion": + def from_db(cls, d: dict[str, Any]) -> ProdegeQuestion: options = None if d["options"]: options = [ @@ -213,7 +213,7 @@ class ProdegeQuestion(MarketplaceQuestion): d["options"] = json.dumps(d["options"]) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/prodege/survey.py b/generalresearch/models/prodege/survey.py index 6c4e4fc..c12f130 100644 --- a/generalresearch/models/prodege/survey.py +++ b/generalresearch/models/prodege/survey.py @@ -55,7 +55,7 @@ class ProdegeCondition(MarketplaceCondition): values: list[str] = Field(validation_alias="precodes") @classmethod - def from_api(cls, d: dict[str, Any]) -> "ProdegeCondition": + def from_api(cls, d: dict[str, Any]) -> ProdegeCondition: assert d["operator"] in { "OR", "NOT", @@ -151,7 +151,7 @@ class ProdegeQuota(BaseModel): } @classmethod - def from_api(cls, d: dict[str, Any]) -> "ProdegeQuota": + def from_api(cls, d: dict[str, Any]) -> ProdegeQuota: # the API doesn't handle None's correctly? idk if d["parent_quota_id"] == 0: d["parent_quota_id"] = None @@ -299,7 +299,7 @@ class ProdegePastParticipation(BaseModel): """ @classmethod - def from_api(cls, d: dict[str, Any]) -> "ProdegePastParticipation": + def from_api(cls, d: dict[str, Any]) -> ProdegePastParticipation: # the API doesn't handle None's correctly? idk if d["in_past_days"] == 0: d["in_past_days"] = None @@ -510,7 +510,7 @@ class ProdegeSurvey(MarketplaceTask): return round(float(v), 2) @classmethod - def from_api(cls, d: dict[str, Any]) -> "ProdegeSurvey | None": + def from_api(cls, d: dict[str, Any]) -> ProdegeSurvey | None: try: return cls._from_api(d) except Exception as e: @@ -518,7 +518,7 @@ class ProdegeSurvey(MarketplaceTask): return None @classmethod - def _from_api(cls, d: dict[str, Any]) -> "ProdegeSurvey": + def _from_api(cls, d: dict[str, Any]) -> ProdegeSurvey: # Handle phases. keys in api response are 'loi' and 'actual_ir' if d["phases"]["loi_phase"] == "actual": @@ -655,7 +655,7 @@ class ProdegeSurvey(MarketplaceTask): return d @classmethod - def from_db(cls, d: dict[str, Any]) -> "ProdegeSurvey": + def from_db(cls, d: dict[str, Any]) -> ProdegeSurvey: d["created"] = d["created"].replace(tzinfo=timezone.utc) d["updated"] = d["updated"].replace(tzinfo=timezone.utc) d["quotas"] = json.loads(d["quotas"]) diff --git a/generalresearch/models/repdata/question.py b/generalresearch/models/repdata/question.py index 95df1e2..8d0da13 100644 --- a/generalresearch/models/repdata/question.py +++ b/generalresearch/models/repdata/question.py @@ -161,7 +161,7 @@ class RepDataQuestion(MarketplaceQuestion): @classmethod def from_api( cls, d: dict[str, Any], country_iso: str, language_iso: str - ) -> "RepDataQuestion | None": + ) -> RepDataQuestion | None: """ :param d: Raw response from API """ @@ -174,7 +174,7 @@ class RepDataQuestion(MarketplaceQuestion): @classmethod def _from_api( cls, d: dict[str, Any], country_iso: str, language_iso: str - ) -> "RepDataQuestion": + ) -> RepDataQuestion: d["QualificationType"] = RepDataQuestionType.from_api(d["QualificationType"]) # zip code/age has a placeholder invalid option for some reason if d["QualificationType"] == RepDataQuestionType.TEXT_ENTRY: @@ -191,7 +191,7 @@ class RepDataQuestion(MarketplaceQuestion): ) @classmethod - def from_db(cls, d: dict[str, Any]) -> "RepDataQuestion": + def from_db(cls, d: dict[str, Any]) -> RepDataQuestion: options = None if d["options"]: options = [ @@ -217,7 +217,7 @@ class RepDataQuestion(MarketplaceQuestion): d["options"] = json.dumps(d["options"]) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/repdata/survey.py b/generalresearch/models/repdata/survey.py index cb204d1..2290ca6 100644 --- a/generalresearch/models/repdata/survey.py +++ b/generalresearch/models/repdata/survey.py @@ -60,7 +60,7 @@ class RepDataCondition(MarketplaceCondition): ) @classmethod - def from_api(cls, d: dict[str, Any]) -> "RepDataCondition": + def from_api(cls, d: dict[str, Any]) -> RepDataCondition: if d["Condition"] == "Is": d["logical_operator"] = LogicalOperator.OR d["negate"] = False @@ -363,7 +363,7 @@ class RepDataStreamHashed(RepDataStream): @classmethod def from_db( cls, res: dict[str, Any], survey: RepDataSurveyHashed - ) -> "RepDataStreamHashed": + ) -> RepDataStreamHashed: # We need certain fields copied over here so that a stream can exist # independent of the survey res["country_iso"] = survey.country_iso @@ -472,7 +472,7 @@ class RepDataSurvey(BaseModel): return ",".join(map(str, sorted([d.value for d in self.allowed_devices]))) @classmethod - def from_api(cls, survey_response) -> "RepDataSurvey | None": + def from_api(cls, survey_response) -> RepDataSurvey | None: """ :param survey_response: Raw response from API """ @@ -486,7 +486,7 @@ class RepDataSurvey(BaseModel): return None @classmethod - def _from_api(cls, survey_response) -> "RepDataSurvey": + def _from_api(cls, survey_response) -> RepDataSurvey: d = survey_response.copy() d["country_iso"] = locale_helper.get_country_iso(d["SurveyCountry"].lower()) d["language_iso"] = locale_helper.get_language_iso(d["SurveyLanguage"].lower()) @@ -521,7 +521,7 @@ class RepDataSurvey(BaseModel): def to_mysql(self) -> dict[str, Any]: return self.to_hashed_survey().to_mysql() - def to_hashed_survey(self) -> "RepDataSurveyHashed": + def to_hashed_survey(self) -> RepDataSurveyHashed: d = self.model_dump(mode="json", exclude={"streams"}) return RepDataSurveyHashed(**d) @@ -533,7 +533,7 @@ class RepDataSurveyHashed(RepDataSurvey): streams: None = Field(default=None, exclude=True) @classmethod - def from_db(cls, res: dict[str, Any]) -> "RepDataSurveyHashed": + def from_db(cls, res: dict[str, Any]) -> RepDataSurveyHashed: res["allowed_devices"] = [ DeviceType(int(x)) for x in res["allowed_devices"].split(",") ] diff --git a/generalresearch/models/sago/question.py b/generalresearch/models/sago/question.py index 6d55c49..f911854 100644 --- a/generalresearch/models/sago/question.py +++ b/generalresearch/models/sago/question.py @@ -173,7 +173,7 @@ class SagoQuestion(MarketplaceQuestion): @classmethod def from_api( cls, d: dict[str, Any], country_iso: str, language_iso: str - ) -> "SagoQuestion | None": + ) -> SagoQuestion | None: """ :param d: Raw response from API :param country_iso: @@ -189,7 +189,7 @@ class SagoQuestion(MarketplaceQuestion): @classmethod def _from_api( cls, d: dict[str, Any], country_iso: str, language_iso: str - ) -> "SagoQuestion": + ) -> SagoQuestion: sago_category_to_tags = { 1: "Standard", 2: "Custom", @@ -223,7 +223,7 @@ class SagoQuestion(MarketplaceQuestion): ) @classmethod - def from_db(cls, d: dict[str, Any]) -> "SagoQuestion": + def from_db(cls, d: dict[str, Any]) -> SagoQuestion: options = None if d["options"]: options = [ @@ -250,7 +250,7 @@ class SagoQuestion(MarketplaceQuestion): d["options"] = json.dumps(d["options"]) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/sago/survey.py b/generalresearch/models/sago/survey.py index 2be6863..e73ddee 100644 --- a/generalresearch/models/sago/survey.py +++ b/generalresearch/models/sago/survey.py @@ -49,7 +49,7 @@ class SagoCondition(MarketplaceCondition): _CONVERT_LIST_TO_RANGE = ["59"] @classmethod - def from_api(cls, d: dict[str, Any]) -> "SagoCondition": + def from_api(cls, d: dict[str, Any]) -> SagoCondition: d["logical_operator"] = LogicalOperator.OR d["value_type"] = ConditionValueType(d["value_type"]) d["negate"] = False @@ -259,7 +259,7 @@ class SagoSurvey(MarketplaceTask): } @classmethod - def from_api(cls, d: dict[str, Any]) -> "SagoSurvey | None": + def from_api(cls, d: dict[str, Any]) -> SagoSurvey | None: try: return cls._from_api(d) except Exception as e: @@ -267,7 +267,7 @@ class SagoSurvey(MarketplaceTask): return None @classmethod - def _from_api(cls, d: dict[str, Any]) -> "SagoSurvey": + def _from_api(cls, d: dict[str, Any]) -> SagoSurvey: return cls.model_validate(d) def __repr__(self) -> str: diff --git a/generalresearch/models/spectrum/question.py b/generalresearch/models/spectrum/question.py index 476e92c..db8a55d 100644 --- a/generalresearch/models/spectrum/question.py +++ b/generalresearch/models/spectrum/question.py @@ -252,7 +252,7 @@ class SpectrumQuestion(MarketplaceQuestion): @classmethod def from_api( cls, d: dict[str, Any], country_iso: str, language_iso: str - ) -> "SpectrumQuestion | None": + ) -> SpectrumQuestion | None: # To not pollute our logs, we know we are skipping any question that # meets the following conditions: if not SpectrumQuestionType.from_api(d["type"]): @@ -336,7 +336,7 @@ class SpectrumQuestion(MarketplaceQuestion): d["created"] = self.created.replace(tzinfo=None) return d - def to_upk_question(self) -> "UpkQuestion": + def to_upk_question(self) -> UpkQuestion: from generalresearch.models.thl.profiling.upk_question import ( UpkQuestion, UpkQuestionChoice, diff --git a/generalresearch/models/spectrum/survey.py b/generalresearch/models/spectrum/survey.py index 0be4d09..a591445 100644 --- a/generalresearch/models/spectrum/survey.py +++ b/generalresearch/models/spectrum/survey.py @@ -65,7 +65,7 @@ class SpectrumCondition(MarketplaceCondition): return self @classmethod - def from_api(cls, d: dict[str, Any]) -> "SpectrumCondition": + def from_api(cls, d: dict[str, Any]) -> SpectrumCondition: """Ranges can get returns with a key "units" indicating years or months. This is ridiculous, and we don't ask for birthdate, so we can't really get month accuracy. Normalize to years. @@ -321,7 +321,7 @@ class SpectrumSurvey(MarketplaceTask): } @classmethod - def from_api(cls, d: dict[str, Any]) -> "SpectrumSurvey | None": + def from_api(cls, d: dict[str, Any]) -> SpectrumSurvey | None: try: return cls._from_api(d) except Exception as e: diff --git a/generalresearch/models/thl/contest/raffle.py b/generalresearch/models/thl/contest/raffle.py index b9a6e31..d3157e3 100644 --- a/generalresearch/models/thl/contest/raffle.py +++ b/generalresearch/models/thl/contest/raffle.py @@ -116,7 +116,7 @@ class RaffleContest(RaffleContestCreate, Contest): ) return self - def select_winners(self) -> list["ContestWinner"]: + def select_winners(self) -> list[ContestWinner]: from generalresearch.models.thl.contest import ContestWinner assert self.is_complete(), "contest must be complete to select a winner" @@ -146,7 +146,7 @@ class RaffleContest(RaffleContestCreate, Contest): return winners - def should_end(self) -> tuple[bool, "ContestEndReason | None"]: + def should_end(self) -> tuple[bool, ContestEndReason | None]: res, msg = super().should_end() if res: return res, msg diff --git a/generalresearch/models/thl/contest/utils.py b/generalresearch/models/thl/contest/utils.py index 5ac2bc1..9250ee4 100644 --- a/generalresearch/models/thl/contest/utils.py +++ b/generalresearch/models/thl/contest/utils.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: from generalresearch.models.thl.user import User -def censor_product_user_id(user: "User") -> str: +def censor_product_user_id(user: User) -> str: s = user.product_user_id if len(s) >= 24: @@ -20,8 +20,8 @@ def censor_product_user_id(user: "User") -> str: def distribute_leaderboard_prizes( - prizes: list["USDCent"], leaderboard_rows: list["LeaderboardRow"] -) -> dict[str, "USDCent"]: + prizes: list[USDCent], leaderboard_rows: list[LeaderboardRow] +) -> dict[str, USDCent]: """ Distributes leaderboard prizes among tied users. The prizes for the tied places are pooled together and divided diff --git a/generalresearch/models/thl/finance.py b/generalresearch/models/thl/finance.py index 9ececc3..08f2456 100644 --- a/generalresearch/models/thl/finance.py +++ b/generalresearch/models/thl/finance.py @@ -38,7 +38,7 @@ class AdjustmentType(BaseModel): "Source of Tasks." ) - adjustment: "SessionAdjustedStatus" = Field( + adjustment: SessionAdjustedStatus = Field( description=SessionAdjustedStatus.as_openapi(), examples=[SessionAdjustedStatus.ADJUSTED_TO_FAIL.value], ) @@ -103,8 +103,8 @@ class POPFinancial(BaseModel): @staticmethod def list_from_pandas( - input_data: pd.DataFrame, accounts: list["LedgerAccount"] - ) -> list["POPFinancial"]: + input_data: pd.DataFrame, accounts: list[LedgerAccount] + ) -> list[POPFinancial]: """ This list can either be for a Product or a Business. The difference is that the list of accounts will either be len()=1 (Product) or @@ -282,7 +282,7 @@ class ProductBalances(BaseModel): # --- Validate --- @model_validator(mode="after") - def check_unknown_fields(self) -> "ProductBalances": + def check_unknown_fields(self) -> ProductBalances: """ I don't fully understand what these fields are supposed to be when looking at bp_wallet accounts. However, I know that they're @@ -469,7 +469,7 @@ class ProductBalances(BaseModel): return_type="USDCent", ) @property - def recoup(self) -> "USDCent": + def recoup(self) -> USDCent: from generalresearch.currency import USDCent if self.balance >= 0: @@ -504,7 +504,7 @@ class ProductBalances(BaseModel): @staticmethod def from_pandas( input_data: pd.DataFrame | pd.Series, - ) -> "ProductBalances": + ) -> ProductBalances: LOG.debug(f"ProductBalances.from_pandas(input_data={input_data.shape})") if isinstance(input_data, pd.Series): @@ -788,7 +788,7 @@ class BusinessBalances(BaseModel): return_type="USDCent", ) @property - def recoup(self) -> "USDCent": + def recoup(self) -> USDCent: """Returns the sum of this Business' recouped amount from any children Products. """ @@ -824,9 +824,9 @@ class BusinessBalances(BaseModel): @staticmethod def from_pandas( input_data: pd.DataFrame, - accounts: List["LedgerAccount"], + accounts: List[LedgerAccount], thl_pg_config: PostgresConfig, - ) -> "BusinessBalances": + ) -> BusinessBalances: LOG.debug(f"BusinessBalances.from_pandas(input_data={input_data.shape})") from generalresearch.incite.schemas.mergers.pop_ledger import ( diff --git a/generalresearch/models/thl/ipinfo.py b/generalresearch/models/thl/ipinfo.py index 5e4e59d..e6a2fcd 100644 --- a/generalresearch/models/thl/ipinfo.py +++ b/generalresearch/models/thl/ipinfo.py @@ -267,7 +267,7 @@ class IPInformation(BaseModel): return self.is_anonymous is None @property - def geoname(self) -> "IPGeoname | None": + def geoname(self) -> IPGeoname | None: return self._geoname or None def normalize_ip(self): diff --git a/generalresearch/models/thl/product.py b/generalresearch/models/thl/product.py index 53f4823..3f21d92 100644 --- a/generalresearch/models/thl/product.py +++ b/generalresearch/models/thl/product.py @@ -416,7 +416,7 @@ class UserWalletConfig(BaseModel): # This field could go in supported_payout_types ---v amt: bool = Field(default=False, description="Uses Amazon Mechanical Turk") - supported_payout_types: set["PayoutType"] = Field( + supported_payout_types: set[PayoutType] = Field( default={PayoutType.CASH_IN_MAIL, PayoutType.TANGO, PayoutType.PAYPAL} ) @@ -430,8 +430,8 @@ class UserWalletConfig(BaseModel): @field_serializer("supported_payout_types", when_used="json") def serialize_supported_payout_types_in_order( - self, supported_payout_types: set["PayoutType"] - ) -> set["PayoutType"]: + self, supported_payout_types: set[PayoutType] + ) -> set[PayoutType]: return set(sorted(supported_payout_types)) @field_validator("min_cashout", mode="after") @@ -888,7 +888,7 @@ class Product(BaseModel, validate_assignment=True): "Payments for this Product's activity.", ) - tags: set["SupplierTag"] = Field( + tags: set[SupplierTag] = Field( default_factory=set, description="Tags which are used to annotate supplier traffic", ) @@ -941,19 +941,19 @@ class Product(BaseModel, validate_assignment=True): # Initialization is deferred until unless it's called # (see .prebuild_***()) - balance: "ProductBalances | None" = Field( + balance: ProductBalances | None = Field( default=None, description="Product Balance" ) payouts_total_str: str | None = Field(default=None) payouts_total: USDCent | None = Field(default=None) - payouts: list["BrokerageProductPayoutEvent"] | None = Field( + payouts: list[BrokerageProductPayoutEvent] | None = Field( default=None, description="Product Payouts. These are the ACH or Wire payments that were sent to the" "Business on behalf of this specific Product", ) - pop_financial: list["POPFinancial"] | None = Field(default=None) + pop_financial: list[POPFinancial] | None = Field(default=None) bp_account: LedgerAccount | None = Field(default=None) # --- Validators --- @@ -1050,7 +1050,7 @@ class Product(BaseModel, validate_assignment=True): return f"product-{self.uuid}" # --- Prefetch --- - def prefetch_bp_account(self, thl_lm: "ThlLedgerManager") -> None: + def prefetch_bp_account(self, thl_lm: ThlLedgerManager) -> None: account = thl_lm.get_account_or_create_bp_wallet(product=self) self.bp_account = account @@ -1058,10 +1058,10 @@ class Product(BaseModel, validate_assignment=True): def prebuild_balance( self, - thl_lm: "ThlLedgerManager", - ds: "GRLDatasets", + thl_lm: ThlLedgerManager, + ds: GRLDatasets, client: Client, - pop_ledger: "PopLedgerMerge | None" = None, + pop_ledger: PopLedgerMerge | None = None, ) -> None: """ This returns the Product's Balances that are calculated across @@ -1139,10 +1139,10 @@ class Product(BaseModel, validate_assignment=True): def prebuild_pop_financial( self, - thl_lm: "ThlLedgerManager", - ds: "GRLDatasets", + thl_lm: ThlLedgerManager, + ds: GRLDatasets, client: Client, - pop_ledger: "PopLedgerMerge | None" = None, + pop_ledger: PopLedgerMerge | None = None, ) -> None: """This is very similar to the Product POP Financial endpoint; however, it returns more than one item for a single time interval. This is @@ -1200,8 +1200,8 @@ class Product(BaseModel, validate_assignment=True): def prebuild_payouts( self, - thl_lm: "ThlLedgerManager", - bp_pem: "BrokerageProductPayoutEventManager", + thl_lm: ThlLedgerManager, + bp_pem: BrokerageProductPayoutEventManager, ) -> None: LOG.debug(f"Product.prebuild_payouts({self.uuid=})") from generalresearch.models.thl.ledger import OrderBy @@ -1311,10 +1311,10 @@ class Product(BaseModel, validate_assignment=True): # --- Methods --- def set_cache( self, - thl_lm: "ThlLedgerManager", - ds: "GRLDatasets", + thl_lm: ThlLedgerManager, + ds: GRLDatasets, client: Client, - bp_pem: "BrokerageProductPayoutEventManager", + bp_pem: BrokerageProductPayoutEventManager, redis_config: RedisConfig, pop_ledger: PopLedgerMerge | None = None, ) -> None: diff --git a/generalresearch/models/thl/profiling/user_question_answer.py b/generalresearch/models/thl/profiling/user_question_answer.py index 0d3e37c..8248623 100644 --- a/generalresearch/models/thl/profiling/user_question_answer.py +++ b/generalresearch/models/thl/profiling/user_question_answer.py @@ -67,7 +67,7 @@ class UserQuestionAnswer(BaseModel): d["session_id"] = session_id return d - def get_mrpqs(self) -> Iterator["MarketplaceResearchProfileQuestion"]: + def get_mrpqs(self) -> Iterator[MarketplaceResearchProfileQuestion]: for k, v in self.calc_answers.items(): source, question_code = k.split(":", 1) yield MarketplaceResearchProfileQuestion( diff --git a/generalresearch/models/thl/session.py b/generalresearch/models/thl/session.py index dc27ba0..17142f3 100644 --- a/generalresearch/models/thl/session.py +++ b/generalresearch/models/thl/session.py @@ -983,7 +983,7 @@ class Session(BaseModel): def determine_payments( self, - thl_ledger_manager: "ThlLedgerManager | None" = None, + thl_ledger_manager: ThlLedgerManager | None = None, ) -> tuple[Decimal, Decimal, Decimal, Decimal | None]: # How much we should get paid by the MPs for all completes in this # session (usually 0 or 1 completes) diff --git a/generalresearch/models/thl/user.py b/generalresearch/models/thl/user.py index 34c9b35..355e331 100644 --- a/generalresearch/models/thl/user.py +++ b/generalresearch/models/thl/user.py @@ -88,14 +88,14 @@ class User(BaseModel): # --- Prefetch Fields --- audit_log: list[AuditLog] | None = Field(default=None) - transactions: list["LedgerTransaction"] | None = Field(default=None) - location_history: list["GeoIPInformation"] | None = Field(default=None) + transactions: list[LedgerTransaction] | None = Field(default=None) + location_history: list[GeoIPInformation] | None = Field(default=None) # --- Prebuild Fields --- # session: Optional[List] = Field(default=None) # wall: Optional[List] = Field(default=None) - def __eq__(self, other: "User"): + def __eq__(self, other: User): return ( self.product_id == other.product_id and self.product_user_id == other.product_user_id @@ -143,14 +143,14 @@ class User(BaseModel): return v @model_validator(mode="after") - def check_identifiable(self) -> "User": + def check_identifiable(self) -> User: if not self.is_identifiable: raise ValueError("User is not identifiable") return self @model_validator(mode="after") - def check_created_first(self) -> "User": + def check_created_first(self) -> User: # TODO: require the created value comes before, or is equal to the # last_seen created = self.created @@ -279,10 +279,10 @@ class User(BaseModel): pm = ProductManager(pg_config=pg_config) self.product = pm.get_by_uuid(product_uuid=self.product_id) - def prefetch_audit_log(self, audit_log_manager: "AuditLogManager") -> None: + def prefetch_audit_log(self, audit_log_manager: AuditLogManager) -> None: self.audit_log = audit_log_manager.filter_by_user_id(user_id=self.user_id) - def prefetch_transactions(self, thl_lm: "ThlLedgerManager") -> None: + def prefetch_transactions(self, thl_lm: ThlLedgerManager) -> None: account = thl_lm.get_account_or_create_user_wallet(user=self) self.transactions = thl_lm.get_tx_filtered_by_account(account_uuid=account.uuid) diff --git a/generalresearch/models/thl/user_iphistory.py b/generalresearch/models/thl/user_iphistory.py index 84ee42e..5892d41 100644 --- a/generalresearch/models/thl/user_iphistory.py +++ b/generalresearch/models/thl/user_iphistory.py @@ -72,7 +72,7 @@ class IPRecord(BaseModel): # On a top-level, this should be an empty list if there are no forwarded_ip. # Within a forwarded_ip record, this should be None. - forwarded_ip_records: list["IPRecord"] | None = Field(default=None, description="") + forwarded_ip_records: list[IPRecord] | None = Field(default=None, description="") information: GeoIPInformation | None = Field(default=None) diff --git a/generalresearch/models/thl/wallet/__init__.py b/generalresearch/models/thl/wallet/__init__.py index e3f5144..1403ddf 100644 --- a/generalresearch/models/thl/wallet/__init__.py +++ b/generalresearch/models/thl/wallet/__init__.py @@ -59,16 +59,16 @@ class Currency(str, Enum): CURRENCY_FORMATTER = { - "USD": lambda x: "${:,.2f}".format(x / 100), - "CAD": lambda x: "${:,.2f} CAD".format(x / 100), - "GBP": lambda x: "{:,.2f} £".format(x / 100), - "EUR": lambda x: "€{:,.2f}".format(x / 100), - "INR": lambda x: "₹{:,.2f}".format(x / 100), - "AUD": lambda x: "${:,.2f} AUD".format(x / 100), - "PLN": lambda x: "{:,.2f} zł".format(x / 100), - "SEK": lambda x: "{:,.2f} kr".format(x / 100), - "SGD": lambda x: "${:,.2f} SGD".format(x / 100), - "MXN": lambda x: "${:,.2f} MXN".format(x / 100), + "USD": lambda x: f"${x / 100:,.2f}", + "CAD": lambda x: f"${x / 100:,.2f} CAD", + "GBP": lambda x: f"{x / 100:,.2f} £", + "EUR": lambda x: f"€{x / 100:,.2f}", + "INR": lambda x: f"₹{x / 100:,.2f}", + "AUD": lambda x: f"${x / 100:,.2f} AUD", + "PLN": lambda x: f"{x / 100:,.2f} zł", + "SEK": lambda x: f"{x / 100:,.2f} kr", + "SGD": lambda x: f"${x / 100:,.2f} SGD", + "MXN": lambda x: f"${x / 100:,.2f} MXN", } # The max value user can redeem in one go in foreign currencies. should be < $250 diff --git a/generalresearch/models/thl/wallet/payout.py b/generalresearch/models/thl/wallet/payout.py index 4b1f5a2..8c78bef 100644 --- a/generalresearch/models/thl/wallet/payout.py +++ b/generalresearch/models/thl/wallet/payout.py @@ -191,7 +191,7 @@ class BPPayoutEvent(BaseModel): payout_events: Collection[PayoutEvent], account_product_mapping: dict[str, str], order_by: str = "ASC", - ) -> list["BPPayoutEvent"]: + ) -> list[BPPayoutEvent]: res = [] for pe in payout_events: bp_pe = BPPayoutEvent.model_validate( diff --git a/generalresearch/sql_helper.py b/generalresearch/sql_helper.py index efdf6f5..2c526f3 100644 --- a/generalresearch/sql_helper.py +++ b/generalresearch/sql_helper.py @@ -131,7 +131,7 @@ def decode_uuids(row: dict[str, Any]) -> dict[str, Any]: class SqlHelper(SqlConnector): def __init__(self, dsn: Optional[DataBaseDsn] = None, **kwargs): - super(SqlHelper, self).__init__(dsn, **kwargs) + super().__init__(dsn, **kwargs) def execute_sql_query( self, query: str, params: dict[str, Any] | None = None, commit: bool = False |
