Is Pythonic classifying objects as empty child classes?

Sorry for the title, I'm not sure how to formulate this question in a more general sense. I am working on a brainfuck parser. The language has 8 types of tokens, which I now present with the following classes:

# Types of lexical tokens class Token: pass class IncPtrToken(Token): pass class DecPtrToken(Token): pass class IncByteToken(Token): pass class DecByteToken(Token): pass class OutputByteToken(Token): pass class InputByteToken(Token): pass class LoopStartToken(Token): pass class LoopEndToken(Token): pass 

In another language, I would probably use an enumeration to represent different types, but this seems like a reasonable alternative in Python.

I read that there are other ways of representing enums in Python, but I think this style is appropriate because some of these objects can carry extra data with them. For example, when representing types of nodes in the parser, a node as a loop will contain an element with nodes inside the loop.

+4
source share
2 answers

Python gets the official Enum class in 3.4.

If you use Python between 2.4 and 3.3 check out the enum34 backport .

You can add other behavior and state to your own Enum class.

+1
source

A type:

 import this 

(also called PEP 20) briefly explains what pythonic is.

"If implementation is hard to explain, it's a bad idea. If implementation is easy to explain, it could be a good idea."

I don’t know how you intend to fulfill your brainwave interpreter. I suppose you do not intend to put specific functions (related to the fact that this ... token) inside ... Token class.

I would use functions or, if they are empty, the list for this is replaced by an enumeration as soon as Py 3.4 is released.

In a nutshell: is it hard to explain? Keep thinking!

+1
source

Source: https://habr.com/ru/post/1499251/


All Articles