10

In my attempt to create a class dots with the fields n and xy as shown below:

from dataclasses import dataclass

@dataclass
class dots:
    n: int = 200
    xy: List[int] = field(default_factory=list)

I am constantly getting the error :

NameError: name 'field' is not defined

Any ideas on how to fix it?

My operating system is Ubuntu 18.04.3 LTS, and the kernel version 4.15.0-58-generic. I am using Python 3.6.4

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Kathia
  • 502
  • 2
  • 7
  • 20
  • 6
    What is `field()` supposed to be? It does not seam to be defined/imported anywhere – Ralf Aug 30 '19 at 14:16

1 Answers1

12

You need to import field() to use it in your code:

from dataclasses import dataclass, field
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Great, it worked -- I don't get this error anymore. However, I got a new error 'NameError: name 'List' is not defined'. I followed the python documentation on how to create an empty list. – Kathia Aug 30 '19 at 14:35
  • 1
    @Kathia you probably need to add `from typing import List` – Ralf Aug 30 '19 at 14:59
  • @Kathia also, are you sure you are running `python 3.6`? `dataclasses` was only added in `3.7` if I'm not mistaken. – Ralf Aug 30 '19 at 15:02
  • yes, I just double-checked and it's ´Python 3.6.4´. I read somewhere that ´dataclasses´ can now work with this version. – Kathia Aug 30 '19 at 15:15
  • 1
    Kathia is right, you can install a backport with `pip install dataclasses` in 3.6 – Arne Aug 31 '19 at 13:59