Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unicode identifiers in Python?

I want to build a Python function that calculates,

alt text

and would like to name my summation function Σ. In a similar fashion, would like to use Π for product, and so on. I was wondering if there was a way to name a python function in this fashion?

def Σ (..):  ..  .. 

That is, does Python support unicode identifiers, and if so, could someone provide an example for it?

Thanks!


Original motivation for this was a piece of Clojure code I saw today that looks like,

(defn entropy [X]       (* -1 (Σ [i X] (* (p i) (log (p i)))))) 

where Σ is a macro defined as,

(defmacro Σ     ... ) 

and I thought that was pretty cool.


BTW, to address a couple of comments about readability - with a lot of stats/ML code for instance, being able to compose operations with symbols would be really helpful. (Especially for really complex integrals et al)

φ(z) = ∫(N(x|0,1,1), -∞, z) 

vs

Phi(z) = integral(N(x|0,1,1), -inf, z) 

or even just the lambda character for lambda()!

like image 716
viksit Avatar asked Apr 15 '10 22:04

viksit


People also ask

What is unicode in Python?

To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of code units, and code units are then mapped to 8-bit bytes.

How do I get unicode in Python?

To include Unicode characters in your Python source code, you can use Unicode escape characters in the form \u0123 in your string. In Python 2. x, you also need to prefix the string literal with 'u'.

Does Python support unicode variable names?

Unicode variable namesPython 3 allows many unicode symbols to be used in variable names. Unlike Julia or Swift, which allow any unicode symbol to represent a variable (including emoji) Python 3 restricts variable names to unicode characters that represent characters in written languages.

What is unicode types of strings in Python?

You can think of unicode as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str . Note: In Python 3, unicode was renamed to str and there is a new bytes type for a plain sequence of bytes.


1 Answers

(I think it’s pretty cool too, that might mean we’re geeks.)

You’re fine to do this with the code you have above in Python 3. (It works in my Python 3.1 interpreter at least.) See:

  • http://docs.python.org/py3k/reference/lexical_analysis.html#identifiers
  • http://www.python.org/dev/peps/pep-3131/

But in Python 2, identifiers can only be ASCII letters, numbers and underscores.

  • http://docs.python.org/reference/lexical_analysis.html#identifiers
like image 150
Paul D. Waite Avatar answered Oct 03 '22 19:10

Paul D. Waite