Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Somewhat cryptic SyntaxError for seemingly ok attribute name #107

Closed
xrotwang opened this issue Oct 27, 2016 · 2 comments
Closed

Somewhat cryptic SyntaxError for seemingly ok attribute name #107

xrotwang opened this issue Oct 27, 2016 · 2 comments

Comments

@xrotwang
Copy link

Some attribute nams which are ok for python are not ok for attrs:

>>> import attr
>>> @attr.s
... class A(object):
...     _1 = attr.ib()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File ".../lib/python2.7/site-packages/attr/_make.py", line 302, in attributes
    return wrap(maybe_cls)
  File ".../lib/python2.7/site-packages/attr/_make.py", line 274, in wrap
    cls = _add_init(cls, frozen)
  File ".../lib/python2.7/site-packages/attr/_make.py", line 453, in _add_init
    bytecode = compile(script, unique_filename, "exec")
  File "<attrs generated init 59333f495b05c926d5d0a4a1c3ea144621198fa1>", line 1
    def __init__(self, 1):
                       ^
SyntaxError: invalid syntax

I know what's going wrong here, but the error is still somewhat cryptic. So I guess this is mostly a documentation issue. But it puzzled me for some time, because I started out with column names in a CSV file - one of them starting with a "2". So pycharm alerted me of the fact that python names cannot start with a number. A "_" prefix made pycharm happy, but upon import of the module, I ran into this issue.

The error I get for a similar case with namedtuple seems more transparent:

>>> from collections import namedtuple
>>> c = namedtuple('c', ['1'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/collections.py", line 337, in namedtuple
    'a number: %r' % name)
ValueError: Type names and field names cannot start with a number: '1'
@wbolster
Copy link
Member

wbolster commented Mar 7, 2017

fwiw, on py3 this may help:

import keyword

def is_valid_attribute_name(s):
    return s.isidentifier() and not keyword.iskeyword(s)

@hynek
Copy link
Member

hynek commented Apr 25, 2018

fixed in #370

@hynek hynek closed this as completed Apr 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants