开发者

Variable with name `None`

I need to have a variable with name None:

class QAbstractPrintDialog(QDialog):
    None = int() # QAbstractPrintDialog.PrintDialogOption enum
    PrintToFile = int() # QAbstractPrintDialog.PrintDialogOption enum
    PrintSelection = int() # QAbstractPrintDialog.PrintDialogOption enum
    ...

But:

syntax error: cannot assign to None

I need the name to be None. I thought this will work:

QAbstractPrintDialog.None = int() # QAbstractPrintDialog.PrintDialogOption enum

But it didn't. Is there a workaround to not have a syntax error? Solutions like setattr don't work for me - this code will be parsed to extract classes, functions, arguments, etc.

Python 2.6, 2.7

开发者_开发问答

EDIT:

I am helping a guy to write pseudo-Python modules which contain description of Qt classes. QAbstractPrintDialog is one of the classes and it has enum QAbstractPrintDialog::PrintDialogOption (http://doc.trolltech.com/latest/qabstractprintdialog.html). One of the enums is None. I can easily reference a None attribute via QAbstractPrintDialog.None but i can not set it. int() means the type of the attribute.

See here: http://scummos.blogspot.com/2011/06/kdevelop-python-language-support-plugin.html


In python None is a reserved word and cannot be used as a variable name. Quoting python documentation:

Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.


You cannot. None is a Python built-in constant.

To do what you are makes no more sense than:

class = struct

"Assignments to None are illegal and raise a SyntaxError." --The documentation

Pick another variable name: nil, none, nothing, zilch, not_a_sausage, no_votes, zero, ...

I agree with you that this is a little inconsistent with other built-in constants, viz:

>>> class Foo:
...     def __init__(self):
...             self.False = True
...             self.True = False
...             self.None = 'Something'
...
  File "<stdin>", line 5
SyntaxError: assignment to None

...but then...

>>> class Foo:
...     def __init__(self):
...             self.False = True
...             self.True = False
...
>>> f = Foo()
>>> f.True
False
>>> f.False
True
>>> f.None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute 'None'

...of course that kind of naming and assignment could only ever lead to trouble!


Call it something distinct like __INSTEADOF_None then strip off all instances of '_INSTEADOF' in a pre-processing step prior to parsing.


It's against the rules to assign to None which has a very special meaning in Python. Choose a different name.


You can try next approach:

>>> class A():pass

>>> a = A()
>>> a.None = 2
SyntaxError: assignment to None
>>> a.__dict__['None'] = 2
>>> a.None
2
>>> dir(a)
['None', '__doc__', '__module__']

But still - idea to use None as object field is really bad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜