2

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.

asked Feb 20, 2016 at 1:08
4
  • Haven't tested, but you may be able to hide it in an exec. Commented Feb 20, 2016 at 1:15
  • 1
    What about globals()['Å'] = angstrom. You probably don't even need your sys.version_info for that one. Commented Feb 20, 2016 at 1:17
  • 1
    Interesting idea by the way . . . Commented Feb 20, 2016 at 1:18
  • @mgilson - globals()['Å'] = angstrom seems to work great, if you add it as an answer I'll accept it. Commented Feb 20, 2016 at 2:24

1 Answer 1

3

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

answered Feb 20, 2016 at 2:55
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.