0
cities = ['LED', 'KUL', 'MOW']
sp = AirwaySpider(cities)

gives the error

sp = AirwaySpider(cities)
TypeError: __init__() takes exactly 1 argument (2 given)

From the AirwaySpider code:

class AirwaySpider(scrapy.Spider):
    def __init__(self, **kw):
        super(AirwaySpider, self).__init__(**kw)
        cities = kw

while this would work

sp = AirwaySpider(domain="sdf")

I understand what the "self" is for, and what is ** in C++, but don't know what this notation means in python and why I can't pass the list where dict (the dict is passed in the example from which I've taken the code) is OK.

UPDATE:

if I change the code to pass raw single argument it works first, but then fails later in the framework:

class AirwaySpider(scrapy.Spider):
    def __init__(self, kw):
        super(AirwaySpider, self).__init__(kw)

error

File "airway.py", line 13, in <module>
process.crawl(sp)
...
File "c:\python27\lib\site-packages\scrapy\crawler.py", line 80, in   _create_spider
return self.spidercls.from_crawler(self, *args, **kwargs)
File "c:\python27\lib\site-packages\scrapy\spiders\__init__.py", line 50, in        from_crawler
spider = cls(*args, **kwargs)
exceptions.TypeError: __init__() takes exactly 2 arguments (1 given)
2015-12-16 15:57:29 [twisted] CRITICAL:
noname7619
  • 3,370
  • 3
  • 21
  • 26

2 Answers2

1

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

Read this link for details: args and kwargs in python explained

So for your function to work need to specify the name of the argument:

sp = AirwaySpider(cities=cities)

k4ppa
  • 4,122
  • 8
  • 26
  • 36
1
def test(a, **args):
    print args  # args is a dict

test(1, prame1=1, parame2=2)

output:

{'parame2': 2, 'parame1': 1}

** can receive all extra parames in the form of 'parame=value' and convert them to dict.

def test(param1, param2):
    print param1
    print param2
param = {'parame1': 1, 'parame2': 2}
test(**param)  
test(prame1=1, parame2=2)  # These two lines are equivalent.

output:

1
2
1
2

When **dict is used as param, it will be converted to 'key=value'

titor
  • 11
  • 2