# Get argument as unicode string from argparse in Python 2 and 3

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(
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?

• Hi, welcome to Code Review. I hope you get great answers! Apr 1 '16 at 8:38

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()


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(