Reputation: 562
I have a python module file which has a bunch of class definition along with its method.
# sample.py
def abc():
...
class Sampler(object):
def foo(self):
...
class Sampler2(object):
def bar(self):
...
Now I want to import this file into another python file and use type annotations while defining a function like below:
# samplers.py
import sample
class Xyz(object):
def foobar(self, sample: sample.Sampler)-> int :
...
The above is throwing AttributeError: module 'sample' has no attribute 'Sampler'
. Is the above implementation incorrect ?
Upvotes: 1
Views: 3807
Reputation: 20425
def foobar(self, sample:sample.Sampler)-> int :
AttributeError: module 'sample' has no attribute 'Sampler'.
The formal parameter is named sample
, yet you imported sample
. Rename the formal parameter (perhaps to sample_
), or use this syntax:
from sample import Sampler
...
def foobar(self, sample: Sampler) -> int:
Cf https://www.python.org/dev/peps/pep-0484/#forward-references, which explains that the use of string literals is also supported. Here, using symbols would be the most appropriate approach.
Upvotes: 1