3
\$\begingroup\$

Code from my last project, that has to work on Python 2.7 and Python 3. I want to get a path as a unicode string from argparse:

parser = argparse.ArgumentParser(
    description='Organize your movie collection using symbolic links')
parser.add_argument('media_src', metavar='FILE|DIR',
                    help='Media file or directory')
args = vars(parser.parse_args(args=argv[1:]))
try:
    args['media_src'] = unicode(args['media_src'], "utf-8",
                                errors="ignore")
except NameError:
    pass  # py3

Can that be done more elegantly without relying on duck typing?

\$\endgroup\$
  • \$\begingroup\$ Hi, welcome to Code Review. I hope you get great answers! \$\endgroup\$ – Tunaki Apr 1 '16 at 8:38
1
\$\begingroup\$

You can define unicode for Python3 when you get a NameError. You should make a small note that explains unicode is not defined in Python3, rather than having the user guess, what #py3 means.

try:
    unicode
except NameError:
    # Define `unicode` for Python3
    def unicode(s, *_):
        return s

You should use the type parameter to add_argument, to change the type returned.
And so if you don't want to have unicode in the global scope in your Python3 environment you can bind it to that functions scope.

def build_to_unicode():
    try:
        unicode
    except NameError:
        def unicode(s, *_):
            return s

    def inner(s):
        return unicode(s, "utf-8")

    return inner

to_unicode = build_to_unicode()

Also your lack of a definitive style to pass variables to the parser made it harder for me to read your code.

try:
    unicode
except NameError:
    # Define `unicode` for Python3
    def unicode(s, *_):
        return s

def to_unicode(s):
    return unicode(s, "utf-8")

parser = argparse.ArgumentParser(
    description='Organize your movie collection using symbolic links')
parser.add_argument(
    'media_src',
    metavar='FILE|DIR',
    help='Media file or directory',
    type=to_unicode)

args = parser.parse_args(args=argv[1:])
# If you really want to.
args = vars(args)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.