Steve Byrnes
Steve Byrnes

Reputation: 2270

unicode identifiers without sacrificing python 2 compatibility

I have a python units package. I want to have both Å and angstrom be two aliases for angstroms, so that people can use whichever one they prefer (Å is easier to read but angstrom is easier to type). Since unicode identifiers are forbidden in Python 2, the Å option will obviously only be available in Python 3. My question is: Is there any way to have a single source file that works in both Python 2 and Python 3, and has this variable defined in Python 3 only?

The naive solution if sys.version_info >= (3,): Å = angstrom does not work, because Python 2 raises a syntax error.

Upvotes: 2

Views: 128

Answers (1)

mgilson
mgilson

Reputation: 310049

Normally, I don't encourage anything other than ascii characters for variable names... However, this is an interesting idea since the angstrom symbol actual has it's standard meaning in this context so I guess I'm cool with it this time :-).

I think you should be able to accomplish this with:

globals()['Å'] = angstrom

and this will "work" on both python2.x and python3.x. Of course, your python2.x users won't be able to reference it in their code without reverting to weird hacks like getattr(units, 'Å'), but it won't throw an error either which is the point of the question (I think).

Upvotes: 3

Related Questions