Package: weatherunits
WeatherUnits️ 🌧Easily convert typical weather units from one unit to another with automatic localization.Features🌈 Effortlessly define or extend your own units☀️ Change nearly every part of unit display from a config.ini file. No need for additional code.❄️ Localization can is as simple as adding .localize to a units variable or setting it to automaticRequirementsPython 3.10How to useNote: The following documentation is currently out of date after some major changesUnit ConversionConversion is as easy as using the desired unit's name or aliases as either an attribute or subscriptfromWeatherUnits.temperatureimportFahrenheit>>>value=Fahrenheit(32)>>>value'32º'>>>value.withUnit'32ºf'>>>value['c'].withUnit'0ºc'>>>value.celcius'0º'Using a Config fileLoading a config fileimportWeatherUnitsaswuwu.config.read('config.ini')A template config file can be found insrc/WeatherUnits/config.  There are three sections in a valid config fileLocalUnits: This is what defines what units you want to use for localizationUnitDefaults: This section holds the default values that apply to every unitUnitProperties: Defines properties for individual units or unit systems as a wholeUnitDefaultsThe basic rules are:Properties are specified without the leading '_'Units are specified with their lowercase names or typesEmpty values will be read as '' and denote being setValues without an '=' will be read as None and denote being unsetPropertiesprecision:The number of digits allowed to be displayed past the decimal but will not exceed max Example number:example3.14159m03m13.1m23.14m33.141mmax:The total number of digits that can be displayed while still showing the decimal.  If shorten is True, numbers would be reduced by factors of 10³example415.25mm20.4k mm3415mm4415.3mm5415.25mmunit:Override built in unit stringsuffix:Override built in suffix string.Only used for shortening numbersdecorator:Override built in decorator.Only used for º with degreestitle:Title to be used by other display programsexp:Override exponent.  I can't imagine why this would be usedshowUnit:Show unit True: 5km False: 5leadingZero:Display zero before values less than 1 True: 0.1in False: .1intrailingZero:Display zero after decimal point to full precision staying under max True: 1.0in False: 1in True: 4.00cmunitSpacer:Determines if there is a space between measurements and their units True: 90º f False: 90ºfkSeparator:valueexampleTrue1,000ftFalse1000ftshorten:Shortens values to fit within the max display amountvalueexampleTrue1k sFalse1000sslide:Scale units for the appropriate values.Not yet implementedvalueexampleTrue1kmFalse1000mcardinal:Show degrees as cardinal direction.Shortendecides full vs abbreviated namevalueexampleTrue180ºFalseSouthkey:Key to be used for other programssizeHint:Override generated size hint string. Useful for when you know the expected max string length.Defining Your Own UnitThere are currently three types of unit,Static,Scaling, andDerivedStatic UnitThe most simple to define. Temperature is an example of a static unit.
Similar units of the same are a subclass of the unit type. In the example below,
Fahrenheit, Celsius, and Kelvin are subclasses of Temperature. Convert to other
similar units with a single private function sharing the name of the desired unit.fromWeatherUnits.baseimportMeasurement,NamedType@NamedType# Unit types are defined with this decorator.classTemperature(Measurement):# For static unit types, the class inherits Measurement.# Shared unit properties are defined here or in a provided config file._decorator='º'# Properties for converting units are defined in the main parent class.@propertydeffahrenheit(self):# Unless all the subunits are defined in the same file, importing the desired# class locally is currently necessary.returnFahrenheit(self._fahrenheit())# Unit abbreviations are defined somewhere below the converting property.f=fahrenheit@propertydefcelsius(self):returnCelsius(self._celsius())c=celsiusclassFahrenheit(Temperature):# Individual unit strings are defined as protected class variables# for each unit or within a config file._unit='f'# This method is what is called to convert Fahrenheit to Celsius.def_celsius(self):# Since Measurement is a float subclass, math can be done on self.return(self-32)/1.8def_fahrenheit(self):# Currently, a function needs to be defined for even converting to the# same unit to prevent errors.returnselfclassCelsius(Temperature):_unit='c'def_celsius(self):returnselfdef_fahrenheit(self):return(self*1.8)+32Scaling UnitScaling units have quite a bit going on.  A scaling unit can be reduced to a single unit through a multiplier, this is the base unit.
Multiple unit systems can be defined within one scale.  It is also to split systems separate scales as long as there is a function within
each system that converts from one base unit to the other.SystemVariant:A class that denotes is not the unit is not within the regular scaleSynonym:Denotes that a unit is the same as an already defined but uses another name. Synonym classes inherit their identically valued classDimension:Decorator that assigns the decorated class to _unitSystem of all child classesBaseUnit:Decorator to define the base unit for the system, this will be used for converting to the non-standard 'SystemVariant'Scale:Uses the metaclass EnumMeta to define the scaling factors for a ScalingMeasurement class along with the multipliers for any SystemVariants
and the base unitTo define a scaling measurement (one that has multiple units within the same unit system, think Centimeter, Meter, Kilometer)
the unit system class inherits ScalingMeasurement.  The main difference from Measurement is the _Scale class defined inside the
main parent class.  In the example below, two unit systems (US and SI) are defined in the same scale.  Most US units
have an SI basis, so this can be done fairly often.  However, it is sometimes necessary to split them for readability.Unified SystemfromWeatherUnits.baseimportNamedType,Synonym,ScalingMeasurementfromWeatherUnits.baseimportScale,BaseUnit,SystemVariant,Dimension@NamedTypeclassPressure(ScalingMeasurement):# The scale for the unit system is defined with by a class named _Scale inheriting.class_Scale(Scale):# Every unit is named here starting with the smallest unit and assigned a# scaling multiplier.  Scaling multipliers here must be an integer.Pascal=1Decapascal=10Hectopascal=10# A base unit is also defined denoted by Base = class.__name__.# Base value must be a string.Base='Pascal'# System variants are units that fall outside of the normal scale# The multiplier value for variants must be a float and be relative# to the base unit.  For example, 1 Bar is 1000 Pascals and# 1 MillimeterOfMercury is 1/0.00750062 or 133.3 Pascals.Bar=1000.Atmosphere=101325.PoundsPerSquareInch=6894.757293168MillimeterOfMercury=1/0.00750062InchOfMercury=1/0.00029530@propertydefpascal(self):returnPascal(self)@propertydefhectopascal(self):returnHectopascal(self)@BaseUnitclassPascal(Pressure):_unit='Pa'classHectopascal(Pressure):_unit='hPa'classAtmosphere(Pascal,SystemVariant):_unit='atm'@SynonymclassMillibar(Hectopascal):_unit='mBar'_max=4Split systemfromWeatherUnits.baseimportNamedType,ScalingMeasurement,Dimension,BaseUnit@NamedTypeclassLength(ScalingMeasurement):@propertydefmeter(self):returnMeter(self)m=meter@propertydeffoot(self):returnFoot(self)ft=footclassImperialLength(Length):class_Scale(Scale):Line=1Inch=12Foot=12Yard=3Mile=1760Base='Foot'# Since the multipliers are defined in _Scale, changeScale() uses one# parameter to change the scale within the same system.def_foot(self):returnself.changeScale(self._Scale.Foot)# This function is called to convert from ImperialLength to MetricLength.  Once its# converted to MetricLength, changeScale() is called within the MetricLength class# to get to the final unit.def_meter(self):returnself._foot()*0.3048@BaseUnitclassFoot(ImperialLength):_unit='ft'@DimensionclassMetricLength(Length):class_Scale(Scale):Millimeter=1Centimeter=10Decimeter=10Meter=10Decameter=10Hectometer=10Kilometer=10Base='Meter'def_meter(self):returnself.changeScale(self._Scale.Meter)# As with the pervious class, this method is called to convert from MetricLength# to ImperialLength.def_foot(self):returnself._meter()*3.280839895013123@BaseUnitclassMeter(MetricLength):_unit='m'Derived UnitDerivedMeasurement is essentially a measurement with multiple units, eg, m/s [meters per second], mph [miles per hour].
Initiation takes in two Measurements and is stored as the dividend of the two.  Both values are independently stored
as protected variables.Note:This type still needs quite a lot of work.  Currently, it only has fractional support, and only a single unit can be used for
both the numerator and denominator.  Eventually this will be expanded allowing for more complex unit derivatives.
Support for the following has not been added:Multiplying two units together, for example a pascal second [Pa·s]Negative exponent units like Hertz [s⁻¹]Multiple units in either the numerator or denominatorfromWeatherUnitsimportLength,TimefromWeatherUnits.baseimportDerivedMeasurement,NamedType,NamedSubType# Summary of the DerivedMeasurement classclassDerivedMeasurement(Measurement):_numerator:Measurement_denominator:Measurementdef__init__(self,numerator,denominator):self._numerator=numeratorself._denominator=denominatorMeasurement.__init__(self,numerator/denominator)@NamedTypeclassDistanceOverTime(DerivedMeasurement):# Defining the unit types for the derived unit helps keep things clear_numerator:Length_denominator:Time# Currently all variations that will be used have to be defined as properties@propertydefmih(self):converted=DistanceOverTime(self._numerator.mi,self._denominator.hr)# Without this override, the unit would be displayed as 'mi/hr'converted._suffix='mph'returnconverted@propertydefms(self):returnDistanceOverTime(self._numerator.m,self._denominator.s)@propertydefkmh(self):returnDistanceOverTime(self._numerator.km,self._denominator.hr)mph=mih@NamedTypeclassPrecipitation(DistanceOverTime):_numerator:Length_denominator:Time@propertydefinh(self):returnPrecipitation(self._numerator.inch,self._denominator.hr)@propertydefmmh(self):returnPrecipitation(self._numerator.mm,self._denominator.hr)@NamedTypeclassPrecipitationRate(Precipitation):pass@NamedSubTypeclassDaily(Precipitation):def__init__(self,numerator:Length,denominator:int=1,*args,**kwargs):ifisinstance(denominator,int):denominator=Time.Day(denominator)Precipitation.__init__(self,numerator,denominator,*args,**kwargs)