Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring : added type annotation #155

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions exifread/classes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re
import struct
from typing import BinaryIO, Dict, Any
from typing import BinaryIO, Dict, Any, List

from exifread.exif_log import get_logger
from exifread.utils import Ratio
Expand All @@ -15,7 +15,7 @@ class IfdTag:
"""

def __init__(self, printable: str, tag: int, field_type: int, values,
field_offset: int, field_length: int):
field_offset: int, field_length: int) -> None:
# printable version of data
self.printable = printable
# tag ID number
Expand Down Expand Up @@ -57,7 +57,7 @@ class ExifHeader:
"""

def __init__(self, file_handle: BinaryIO, endian, offset, fake_exif, strict: bool,
debug=False, detailed=True, truncate_tags=True):
debug=False, detailed=True, truncate_tags=True) -> None:
self.file_handle = file_handle
self.endian = endian
self.offset = offset
Expand Down Expand Up @@ -142,7 +142,7 @@ def list_ifd(self) -> list:
i = self._next_ifd(i)
return ifds

def _process_field(self, tag_name, count, field_type, type_length, offset):
def _process_field(self, tag_name, count, field_type, type_length, offset) -> List:
values = []
signed = (field_type in [6, 8, 9, 10])
# XXX investigate
Expand Down Expand Up @@ -188,7 +188,7 @@ def _process_field(self, tag_name, count, field_type, type_length, offset):
offset = offset + type_length
return values

def _process_field2(self, ifd_name, tag_name, count, offset):
def _process_field2(self, ifd_name, tag_name, count, offset) -> str:
values = ''
# special case: null-terminated ASCII string
# XXX investigate
Expand Down Expand Up @@ -532,7 +532,7 @@ def decode_maker_note(self) -> None:
# def _olympus_decode_tag(self, value, mn_tags):
# pass

def _canon_decode_tag(self, value, mn_tags):
def _canon_decode_tag(self, value, mn_tags) -> None:
"""
Decode Canon MakerNote tag based on offset within tag.

Expand All @@ -554,7 +554,7 @@ def _canon_decode_tag(self, value, mn_tags):
# This will have a "proprietary" type
self.tags['MakerNote ' + name] = IfdTag(str(val), 0, 0, val, 0, 0)

def _canon_decode_camera_info(self, camera_info_tag):
def _canon_decode_camera_info(self, camera_info_tag) -> None:
"""
Decode the variable length encoded camera info section.
"""
Expand Down Expand Up @@ -596,7 +596,7 @@ def _canon_decode_camera_info(self, camera_info_tag):

self.tags['MakerNote ' + tag_name] = IfdTag(str(tag_value), 0, 0, tag_value, 0, 0)

def parse_xmp(self, xmp_bytes: bytes):
def parse_xmp(self, xmp_bytes: bytes) -> None:
"""Adobe's Extensible Metadata Platform, just dump the pretty XML."""

import xml.dom.minidom # pylint: disable=import-outside-toplevel
Expand Down
10 changes: 5 additions & 5 deletions exifread/exif_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
TEXT_CYAN = 36


def get_logger():
def get_logger() -> logging.Logger:
"""Use this from all files needing to log."""
return logging.getLogger("exifread")


def setup_logger(debug, color):
def setup_logger(debug, color) -> None:
"""Configure the logger."""

if debug:
Expand All @@ -39,7 +39,7 @@ class Formatter(logging.Formatter):
Custom formatter, we like colors!
"""

def __init__(self, debug=False, color=False):
def __init__(self, debug=False, color=False) -> None:
self.color = color
self.debug = debug
if self.debug:
Expand All @@ -48,7 +48,7 @@ def __init__(self, debug=False, color=False):
log_format = "%(message)s"
logging.Formatter.__init__(self, log_format)

def format(self, record):
def format(self, record) -> str:
if self.debug and self.color:
if record.levelno >= logging.CRITICAL:
color = TEXT_RED
Expand All @@ -67,7 +67,7 @@ def format(self, record):


class Handler(logging.StreamHandler):
def __init__(self, log_level, debug=False, color=False):
def __init__(self, log_level, debug=False, color=False) -> None:
self.color = color
self.debug = debug
logging.StreamHandler.__init__(self, sys.stdout)
Expand Down
28 changes: 14 additions & 14 deletions exifread/heic.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# gives us position and size information.

import struct
from typing import Any, List, Dict, Callable, BinaryIO, Optional
from typing import Any, List, Dict, Callable, BinaryIO, Optional, Tuple

from exifread.exif_log import get_logger

Expand Down Expand Up @@ -50,19 +50,19 @@ class Box:
index_size = 0
flags = 0

def __init__(self, name: str):
def __init__(self, name: str) -> None:
self.name = name

def __repr__(self) -> str:
return "<box '%s'>" % self.name

def set_sizes(self, offset: int, length: int, base_offset: int, index: int):
def set_sizes(self, offset: int, length: int, base_offset: int, index: int) -> None:
self.offset_size = offset
self.length_size = length
self.base_offset_size = base_offset
self.index_size = index

def set_full(self, vflags: int):
def set_full(self, vflags: int) -> None:
"""
ISO boxes come in 'old' and 'full' variants.
The 'full' variant contains version and flags information.
Expand All @@ -73,7 +73,7 @@ def set_full(self, vflags: int):

class HEICExifFinder:

def __init__(self, file_handle: BinaryIO):
def __init__(self, file_handle: BinaryIO) -> None:
self.file_handle = file_handle

def get(self, nbytes: int) -> bytes:
Expand All @@ -98,7 +98,7 @@ def get32(self) -> int:
def get64(self) -> int:
return struct.unpack('>Q', self.get(8))[0]

def get_int4x2(self) -> tuple:
def get_int4x2(self) -> Tuple:
num = struct.unpack('>B', self.get(1))[0]
num0 = num >> 4
num1 = num & 0xf
Expand Down Expand Up @@ -144,10 +144,10 @@ def next_box(self) -> Box:
box.pos = self.file_handle.tell()
return box

def get_full(self, box: Box):
def get_full(self, box: Box) -> None:
box.set_full(self.get32())

def skip(self, box: Box):
def skip(self, box: Box) -> None:
self.file_handle.seek(box.after)

def expect_parse(self, name: str) -> Box:
Expand Down Expand Up @@ -175,7 +175,7 @@ def parse_box(self, box: Box) -> Box:
self.file_handle.seek(box.after)
return box

def _parse_ftyp(self, box: Box):
def _parse_ftyp(self, box: Box) -> None:
box.major_brand = self.get(4)
box.minor_version = self.get32()
box.compat = []
Expand All @@ -184,7 +184,7 @@ def _parse_ftyp(self, box: Box):
box.compat.append(self.get(4))
size -= 4

def _parse_meta(self, meta: Box):
def _parse_meta(self, meta: Box) -> None:
self.get_full(meta)
while self.file_handle.tell() < meta.after:
box = self.next_box()
Expand All @@ -197,7 +197,7 @@ def _parse_meta(self, meta: Box):
# skip any unparsed data
self.skip(box)

def _parse_infe(self, box: Box):
def _parse_infe(self, box: Box) -> None:
self.get_full(box)
if box.version >= 2:
if box.version == 2:
Expand All @@ -209,7 +209,7 @@ def _parse_infe(self, box: Box):
box.item_name = self.get_string()
# ignore the rest

def _parse_iinf(self, box: Box):
def _parse_iinf(self, box: Box) -> None:
self.get_full(box)
count = self.get16()
box.exif_infe = None
Expand All @@ -220,7 +220,7 @@ def _parse_iinf(self, box: Box):
box.exif_infe = infe
break

def _parse_iloc(self, box: Box):
def _parse_iloc(self, box: Box) -> None:
self.get_full(box)
size0, size1 = self.get_int4x2()
size2, size3 = self.get_int4x2()
Expand Down Expand Up @@ -257,7 +257,7 @@ def _parse_iloc(self, box: Box):
extents.append((extent_offset, extent_length))
box.locs[item_id] = extents

def find_exif(self) -> tuple:
def find_exif(self) -> Tuple:
ftyp = self.expect_parse('ftyp')
assert ftyp.major_brand == b'heic'
assert ftyp.minor_version == 0
Expand Down
12 changes: 6 additions & 6 deletions exifread/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
"""

from fractions import Fraction
from typing import Union
from typing import Any, Tuple, Union


def ord_(dta):
def ord_(dta) -> int:
if isinstance(dta, str):
return ord(dta)
return dta
Expand Down Expand Up @@ -53,7 +53,7 @@ def make_string_uc(seq) -> str:
return make_string(seq)


def get_gps_coords(tags: dict) -> tuple:
def get_gps_coords(tags: dict) -> Tuple:

lng_ref_tag_name = 'GPS GPSLongitudeRef'
lng_tag_name = 'GPS GPSLongitude'
Expand Down Expand Up @@ -88,7 +88,7 @@ class Ratio(Fraction):
"""

# We're immutable, so use __new__ not __init__
def __new__(cls, numerator=0, denominator=None):
def __new__(cls, numerator=0, denominator=None) -> Any:
try:
self = super(Ratio, cls).__new__(cls, numerator, denominator)
except ZeroDivisionError:
Expand All @@ -101,11 +101,11 @@ def __repr__(self) -> str:
return str(self)

@property
def num(self):
def num(self) -> int:
return self.numerator

@property
def den(self):
def den(self) -> int:
return self.denominator

def decimal(self) -> float:
Expand Down