Skip to content

Instantly share code, notes, and snippets.

@dgjustice
Created May 27, 2020
Embed
What would you like to do?
from pydantic import BaseModel
import requests
from returns.context import RequiresContext
from returns.functions import tap
from returns.io import IOResultE, impure_safe
class OVHIpAddr(BaseModel):
ip: str
ip_decimal: int
country: str
country_eu: bool
country_iso: str
city: str
hostname: str
latitude: float
longitude: float
asn: str
asn_org: str
def get_ip_addr() -> RequiresContext[str, IOResultE[OVHIpAddr]]:
"""Get our IP address from a service"""
@impure_safe
def inner(url: str) -> OVHIpAddr:
resp = requests.get(url)
return OVHIpAddr(**resp.json())
return RequiresContext(inner)
def format_city_country(data: OVHIpAddr) -> str:
"""Format the city and country"""
return f"{data.city}, {data.country}"
if __name__ == "__main__":
# Works
(
get_ip_addr()("https://whatsmyip.ovh/json")
.map(format_city_country)
.map(tap(print))
)
# AttributeError: '_IOSuccess' object has no attribute 'city'
# error: Argument 1 to "map" of "RequiresContext" has incompatible type "Callable[[OVHIpAddr], str]"; expected "Callable[[IOResult[OVHIpAddr, Exception]], str]"
(
get_ip_addr()
.map(format_city_country)
.map(tap(print))("https://whatsmyip.ovh/json")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment