Python-сообщество
- Начало
- » Python для новичков
- » борьба с кодировками
#1 Апрель 13, 2012 22:47:29
xenon От: Зарегистрирован: 2010-12-03 Сообщения: 23 Репутация: 0 Профиль Отправить e-mail
борьба с кодировками
Доброе время суток.
подскажите пожалуйста с решением проблемы:
есть словарь вида:
Species_cod=
также есть файл (.txt), в котором одна из колонок составляет буквы, перечисленные в словаре.
я считываю строку из файла, вычлиняю из нее нужную мне букву (из нужной колонки) и хочу заменить ее на значение из словаря, но тут встает проблема с кодировкой.
Попробовал перекодировать букву из файла так:
species=numbers[4].decode('cp1251')
на экран выводит читабельно, но дальше для записи в матрицу значений по словарю:
Species[i,j]=Species_cod(species)
не работает, пишет ошибку:
ОС
Traceback (most recent call last):
File "C:\Python27\grid_10m.py", line 45, in
Species[i,j]=Species_cod(species) # ╨║╨░╨║-╤В╨╛ ╨┐╨╡╤А╨╡╨▓╨╛╨┤╨╕╤В╤М ╨▓ ╤З╨╕
╤Б╨╗╨╛╨▓╨╛╨╡ ╨╖╨╜╨░╤З╨╡╨╜╨╕╨╡ ╤З╨╡╤А╨╡╨╖ ╤И╨╕╤Д╤А
TypeError: 'dict' object is not callable
Помогите пожалуйста, что я делаю не так, весь лоб уже об эти кодировки расколотил, а закона (правила) их применения не понял …
Мыши плакали, кололись, но продолжали жрать кактус …
Отредактировано xenon (Апрель 13, 2012 22:49:48)
При создании словаря в Python 2.7 TypeError: ‘dict’ object is not callable
Хочу составить словарь из двухмерного списка, где в тексте каждое предложение в отдельном массиве.
counts = dict() for line in new: for word in line: if word not in counts: counts[word] = 1 else: counts[word] += 1 print counts
Выдает ошибку
TypeError Traceback (most recent call last) in () ----> 1 counts = dict() 2 for line in new: 3 for word in line: 4 if word not in counts: 5 counts[word] = 1 TypeError: 'dict' object is not callable
Отслеживать
49.3k 17 17 золотых знаков 57 57 серебряных знаков 101 101 бронзовый знак
Saved searches
Use saved searches to filter your results more quickly
Cancel Create saved search
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
bentoml / OpenLLM Public
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
bug: When running by example getting error: TypeError: ‘dict’ object is not callable #732
lolevsky opened this issue Nov 26, 2023 · 6 comments
bug: When running by example getting error: TypeError: ‘dict’ object is not callable #732
lolevsky opened this issue Nov 26, 2023 · 6 comments
Comments
lolevsky commented Nov 26, 2023
Describe the bug
I am following the example and wrote the code:
llm = OpenLLM(server_url=server_url, server_type='http') llm("What is the difference between a duck and a goose? And why there are so many Goose in Canada?")
Seems like First request is hitting the server
(scheme=http,method=POST,path=/v1/metadata,type=application/json,length=2) (status=200
Till now its look promising, but then I am getting error TypeError: ‘dict’ object is not callable .
As attached in the trace:
Traceback (most recent call last): File "/home/lolevsky/Github/Zodiac/main.py", line 24, in run_zodiac() File "/home/lolevsky/Github/Zodiac/main.py", line 9, in run_zodiac resA = llm("What is the difference between a duck and a goose? And why there are so many Goose in Canada?") File "/usr/local/lib/python3.10/dist-packages/langchain/llms/base.py", line 876, in __call__ self.generate( File "/usr/local/lib/python3.10/dist-packages/langchain/llms/base.py", line 626, in generate params = self.dict() File "/usr/local/lib/python3.10/dist-packages/langchain/llms/base.py", line 974, in dict starter_dict = dict(self._identifying_params) File "/usr/local/lib/python3.10/dist-packages/langchain/llms/openllm.py", line 220, in _identifying_params self.llm_kwargs.update(self._client._config()) TypeError: 'dict' object is not callable
To reproduce
This is how I had setup the envirment:
- conda create —name openllm python=3.11
- conda activate openllm
- pip install openllm
- pip install langchain
Logs
Environment
Environment variable
BENTOML_DEBUG='' BENTOML_QUIET='' BENTOML_BUNDLE_LOCAL_BUILD='' BENTOML_DO_NOT_TRACK='' BENTOML_CONFIG='' BENTOML_CONFIG_OPTIONS='' BENTOML_PORT='' BENTOML_HOST='' BENTOML_API_WORKERS=''
System information
bentoml : 1.1.10
python : 3.11.5
platform : Linux-6.2.0-37-generic-x86_64-with-glibc2.35
uid_gid : 1000:1000
conda : 23.7.4
in_conda_env : True
name: openllm channels: - defaults dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h7b6447c_0 - ca-certificates=2023.08.22=h06a4308_0 - ld_impl_linux-64=2.38=h1181459_1 - libffi=3.4.4=h6a678d5_0 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.12=h7f8727e_0 - pip=23.3.1=py311h06a4308_0 - python=3.11.5=h955ad1f_0 - readline=8.2=h5eee18b_0 - setuptools=68.0.0=py311h06a4308_0 - sqlite=3.41.2=h5eee18b_0 - tk=8.6.12=h1ccaba5_0 - wheel=0.41.2=py311h06a4308_0 - xz=5.4.2=h5eee18b_0 - zlib=1.2.13=h5eee18b_0 - pip: - accelerate==0.24.1 - aiohttp==3.9.0 - aiosignal==1.3.1 - anyio==3.7.1 - appdirs==1.4.4 - asgiref==3.7.2 - attrs==23.1.0 - beautifulsoup4==4.12.2 - bentoml==1.1.10 - bitsandbytes==0.41.2.post2 - build==0.10.0 - cattrs==23.1.2 - certifi==2023.11.17 - charset-normalizer==3.3.2 - circus==0.18.0 - click==8.1.7 - click-option-group==0.5.6 - cloudpickle==3.0.0 - coloredlogs==15.0.1 - contextlib2==21.6.0 - cuda-python==12.3.0 - dataclasses-json==0.6.2 - datasets==2.15.0 - deepmerge==1.1.0 - deprecated==1.2.14 - dill==0.3.7 - distlib==0.3.7 - distro==1.8.0 - einops==0.7.0 - fastapi==0.104.1 - fastcore==1.5.29 - filelock==3.13.1 - filetype==1.2.0 - frozenlist==1.4.0 - fs==2.4.16 - fsspec==2023.10.0 - ghapi==1.0.4 - greenlet==3.0.1 - h11==0.14.0 - httpcore==1.0.2 - httptools==0.6.1 - httpx==0.25.2 - huggingface-hub==0.19.4 - humanfriendly==10.0 - idna==3.6 - importlib-metadata==6.8.0 - inflection==0.5.1 - jinja2==3.1.2 - jsonpatch==1.33 - jsonpointer==2.4 - jsonschema==4.20.0 - jsonschema-specifications==2023.11.1 - langchain==0.0.340 - langsmith==0.0.66 - markdown-it-py==3.0.0 - markupsafe==2.1.3 - marshmallow==3.20.1 - mdurl==0.1.2 - mpmath==1.3.0 - msgpack==1.0.7 - multidict==6.0.4 - multiprocess==0.70.15 - mypy-extensions==1.0.0 - networkx==3.2.1 - ninja==1.11.1.1 - numpy==1.26.2 - nvidia-cublas-cu12==12.1.3.1 - nvidia-cuda-cupti-cu12==12.1.105 - nvidia-cuda-nvrtc-cu12==12.1.105 - nvidia-cuda-runtime-cu12==12.1.105 - nvidia-cudnn-cu12==8.9.2.26 - nvidia-cufft-cu12==11.0.2.54 - nvidia-curand-cu12==10.3.2.106 - nvidia-cusolver-cu12==11.4.5.107 - nvidia-cusparse-cu12==12.1.0.106 - nvidia-ml-py==11.525.150 - nvidia-nccl-cu12==2.18.1 - nvidia-nvjitlink-cu12==12.3.101 - nvidia-nvtx-cu12==12.1.105 - openllm==0.4.28 - openllm-client==0.4.28 - openllm-core==0.4.28 - opentelemetry-api==1.20.0 - opentelemetry-instrumentation==0.41b0 - opentelemetry-instrumentation-aiohttp-client==0.41b0 - opentelemetry-instrumentation-asgi==0.41b0 - opentelemetry-sdk==1.20.0 - opentelemetry-semantic-conventions==0.41b0 - opentelemetry-util-http==0.41b0 - optimum==1.14.1 - orjson==3.9.10 - packaging==23.2 - pandas==2.1.3 - pathspec==0.11.2 - pillow==10.1.0 - pip-requirements-parser==32.0.1 - pip-tools==7.3.0 - platformdirs==4.0.0 - prometheus-client==0.19.0 - protobuf==4.25.1 - psutil==5.9.6 - pyarrow==14.0.1 - pyarrow-hotfix==0.6 - pydantic==1.10.13 - pygments==2.17.2 - pyparsing==3.1.1 - pyproject-hooks==1.0.0 - python-dateutil==2.8.2 - python-dotenv==1.0.0 - python-json-logger==2.0.7 - python-multipart==0.0.6 - pytz==2023.3.post1 - pyyaml==6.0.1 - pyzmq==25.1.1 - ray==2.8.0 - referencing==0.31.0 - regex==2023.10.3 - requests==2.31.0 - rich==13.7.0 - rpds-py==0.13.1 - safetensors==0.4.0 - schema==0.7.5 - scipy==1.11.4 - sentencepiece==0.1.99 - simple-di==0.1.5 - six==1.16.0 - sniffio==1.3.0 - soupsieve==2.5 - sqlalchemy==2.0.23 - starlette==0.27.0 - sympy==1.12 - tenacity==8.2.3 - tokenizers==0.15.0 - torch==2.1.0 - tornado==6.3.3 - tqdm==4.66.1 - transformers==4.35.2 - triton==2.1.0 - typing-extensions==4.8.0 - typing-inspect==0.9.0 - tzdata==2023.3 - urllib3==2.1.0 - uvicorn==0.24.0.post1 - uvloop==0.19.0 - virtualenv==20.24.7 - vllm==0.2.2 - watchfiles==0.21.0 - websockets==12.0 - wrapt==1.16.0 - xformers==0.0.22.post7 - xxhash==3.4.1 - yarl==1.9.3 - zipp==3.17.0 prefix: /home/lolevsky/anaconda3/envs/openllm
pip_packages
accelerate==0.24.1 aiohttp==3.9.0 aiosignal==1.3.1 anyio==3.7.1 appdirs==1.4.4 asgiref==3.7.2 attrs==23.1.0 beautifulsoup4==4.12.2 bentoml==1.1.10 bitsandbytes==0.41.2.post2 build==0.10.0 cattrs==23.1.2 certifi==2023.11.17 charset-normalizer==3.3.2 circus==0.18.0 click==8.1.7 click-option-group==0.5.6 cloudpickle==3.0.0 coloredlogs==15.0.1 contextlib2==21.6.0 cuda-python==12.3.0 dataclasses-json==0.6.2 datasets==2.15.0 deepmerge==1.1.0 Deprecated==1.2.14 dill==0.3.7 distlib==0.3.7 distro==1.8.0 einops==0.7.0 fastapi==0.104.1 fastcore==1.5.29 filelock==3.13.1 filetype==1.2.0 frozenlist==1.4.0 fs==2.4.16 fsspec==2023.10.0 ghapi==1.0.4 greenlet==3.0.1 h11==0.14.0 httpcore==1.0.2 httptools==0.6.1 httpx==0.25.2 huggingface-hub==0.19.4 humanfriendly==10.0 idna==3.6 importlib-metadata==6.8.0 inflection==0.5.1 Jinja2==3.1.2 jsonpatch==1.33 jsonpointer==2.4 jsonschema==4.20.0 jsonschema-specifications==2023.11.1 langchain==0.0.340 langsmith==0.0.66 markdown-it-py==3.0.0 MarkupSafe==2.1.3 marshmallow==3.20.1 mdurl==0.1.2 mpmath==1.3.0 msgpack==1.0.7 multidict==6.0.4 multiprocess==0.70.15 mypy-extensions==1.0.0 networkx==3.2.1 ninja==1.11.1.1 numpy==1.26.2 nvidia-cublas-cu12==12.1.3.1 nvidia-cuda-cupti-cu12==12.1.105 nvidia-cuda-nvrtc-cu12==12.1.105 nvidia-cuda-runtime-cu12==12.1.105 nvidia-cudnn-cu12==8.9.2.26 nvidia-cufft-cu12==11.0.2.54 nvidia-curand-cu12==10.3.2.106 nvidia-cusolver-cu12==11.4.5.107 nvidia-cusparse-cu12==12.1.0.106 nvidia-ml-py==11.525.150 nvidia-nccl-cu12==2.18.1 nvidia-nvjitlink-cu12==12.3.101 nvidia-nvtx-cu12==12.1.105 openllm==0.4.28 openllm-client==0.4.28 openllm-core==0.4.28 opentelemetry-api==1.20.0 opentelemetry-instrumentation==0.41b0 opentelemetry-instrumentation-aiohttp-client==0.41b0 opentelemetry-instrumentation-asgi==0.41b0 opentelemetry-sdk==1.20.0 opentelemetry-semantic-conventions==0.41b0 opentelemetry-util-http==0.41b0 optimum==1.14.1 orjson==3.9.10 packaging==23.2 pandas==2.1.3 pathspec==0.11.2 Pillow==10.1.0 pip-requirements-parser==32.0.1 pip-tools==7.3.0 platformdirs==4.0.0 prometheus-client==0.19.0 protobuf==4.25.1 psutil==5.9.6 pyarrow==14.0.1 pyarrow-hotfix==0.6 pydantic==1.10.13 Pygments==2.17.2 pyparsing==3.1.1 pyproject_hooks==1.0.0 python-dateutil==2.8.2 python-dotenv==1.0.0 python-json-logger==2.0.7 python-multipart==0.0.6 pytz==2023.3.post1 PyYAML==6.0.1 pyzmq==25.1.1 ray==2.8.0 referencing==0.31.0 regex==2023.10.3 requests==2.31.0 rich==13.7.0 rpds-py==0.13.1 safetensors==0.4.0 schema==0.7.5 scipy==1.11.4 sentencepiece==0.1.99 simple-di==0.1.5 six==1.16.0 sniffio==1.3.0 soupsieve==2.5 SQLAlchemy==2.0.23 starlette==0.27.0 sympy==1.12 tenacity==8.2.3 tokenizers==0.15.0 torch==2.1.0 tornado==6.3.3 tqdm==4.66.1 transformers==4.35.2 triton==2.1.0 typing-inspect==0.9.0 typing_extensions==4.8.0 tzdata==2023.3 urllib3==2.1.0 uvicorn==0.24.0.post1 uvloop==0.19.0 virtualenv==20.24.7 vllm==0.2.2 watchfiles==0.21.0 websockets==12.0 wrapt==1.16.0 xformers==0.0.22.post7 xxhash==3.4.1 yarl==1.9.3 zipp==3.17.0
System information (Optional)
The text was updated successfully, but these errors were encountered:
Python 3.8: TypeError: ‘dict’ object is not callable when trying to get data from a file
ran into a roadblock during a tutorial. I have no idea on how to solve this. I’m trying to use data from a csv file. When I try accessing the data with the current code commented out (see below), it works by outputting existing data. However, it immediately errors when I add back in the commented code, with the error mentioned in the title. Could someone look at this and tell me what I’ve done wrong?
import csv class item: pay_rate = 0.8 #the payrate after 20% discount all = [] def __init__(self, name: str, price: float, quantity: int = 0): #run validations of received arguments assert price >= 0, f"price !> 0" assert quantity >= 0, f"quantity !> 0" #assign to self object print(f"an instance created: ") self.name = name self.price = price self.quantity = quantity #actions to execute item.all.append(self) def calculate_total_price(self): return self.price * self.quantity def apply_discount(self): self.price = self.price * self.pay_rate @classmethod def instantiate_from_csv(cls): with open('items.csv', 'r') as f: reader = csv.DictReader(f) items = list(reader) for item in items: item( name=item.get('name'), price=float(item.get('price')), quantity=int(item.get('quantity')), ) def __repr__(self): return f"item(,, )" item.instantiate_from_csv() print(item.all)
744k 179 179 gold badges 1.4k 1.4k silver badges 1.5k 1.5k bronze badges
asked Jun 23, 2022 at 22:18
user2211420 user2211420
11 3 3 bronze badges
What did you expect that to do? item is the name of a dictionary. What is your objective with that? And is that in a class called item ? Do not reuse names like that. It just leads to confusion.
Jun 23, 2022 at 22:20
Why is the code raising the exception commented out?
Jun 23, 2022 at 22:22
item is a dict . What do you expect item(. ) to do? Are you maybe trying to create an instance of class Item ? That would be item=Item(. ) .
Jun 23, 2022 at 22:23
You’re using item like it can be anything at any time. Even in Python, that’s not possible.
Jun 23, 2022 at 22:25
You’ve named everything item and managed to confuse even yourself. But clearly the item causing the issue is the one where you are looping over a list of dictionaries, calling each dict element in the list item and then trying to access that dictionary as if it were the constructor of the class you also called item . Start by renaming the various things you named item to be something more descriptive and distinctive, and you’ll see that the problem is obvious then.
Jun 23, 2022 at 23:10
1 Answer 1
By naming several things item , you managed to confuse even yourself.
Below is your code with things sensibly renamed and the problem fixed. Take a look at the comments to see what was changed:
import csv # renamed to AllItems, because that's what you end up using it for # you're mixing up an instance and a container of instances here and # it gets you the worst of both worlds class AllItems: pay_rate = 0.8 all = [] def __init__(self, name: str, price: float, quantity: int = 0): assert price >= 0, f"price !> 0" assert quantity >= 0, f"quantity !> 0" print(f"an instance created: ") self.name = name self.price = price self.quantity = quantity # you can do this, but you in some cases you want to use # self.all.append instead, which will still access the class # attribute AllItems.all.append(self) def calculate_total_price(self): return self.price * self.quantity def apply_discount(self): # this is dubious - can you apply the same discount many times? self.price = self.price * self.pay_rate # renamed to 'load', sure you instantiate, but you don't return the # instance, you're really just abusing the class as a container @classmethod def load_from_csv(cls, fn): # it seems to make more sense to be able to use different csvs? with open(fn, 'r') as f: reader = csv.DictReader(f) item_dr = list(reader) for item_dict in item_dr: # your problem was right here, you referred to `item()` where # you meant to refer to the class, which is already passed as `cls` cls( name=item_dict.get('name'), price=float(item_dict.get('price')), quantity=int(item_dict.get('quantity')), ) def __repr__(self): # I'm not fixing this, but see remark below return f"item(,, )" AllItems.load_from_csv('items.csv') # confusing double `.all` here, didn't bother improving the naming # considering that it's the result of the design decision you made print(AllItems.all)
For an items.csv with this:
name,price,quantity banana,10,12 apple,4,6 pear,7,6
an instance created: banana an instance created: apple an instance created: pear [item(banana,10.0, 12), item(apple,4.0, 6), item(pear,7.0, 6)]
Note that this fixes your issue but still leaves your code with some serious problems:
- You’re using the class as a container; that works, but it’s not a great way of using a class like this and it certainly won’t be what others expect. You’re robbing yourself of all of the features a better container like a list would get you, like the it being iterable, or a dict , which would allow easy lookup of products (items). Consider creating an Item class that is just the Item and an Items (or something better) class that contains items and has additional operations.
- Note that your representation __repr__ really doesn’t give you a representation, that’s not how someone could recreate the class at all and it’s probably more of a __str__
Here’s an example of what I’m suggesting:
import csv class Item: pay_rate = 0.8 def __init__(self, name: str, price: float, quantity: int = 0): assert price >= 0, f"price !> 0" assert quantity >= 0, f"quantity !> 0" self.name = name self._price = price self.quantity = quantity self.discount = None @property def price(self): if self.discount is None: return self._price else: return self._price * self.discount @property def total_price(self): return self.price * self.quantity def apply_pay_rate(self): self.discount = self.pay_rate @classmethod def item_list_from_csv(cls, fn): with open(fn, 'r') as f: reader = csv.DictReader(f) item_dr = list(reader) return [cls( name=item_dict.get('name'), price=float(item_dict.get('price')), quantity=int(item_dict.get('quantity')), ) for item_dict in item_dr] def __repr__(self): return f"Item(, , )" item_list = Item.item_list_from_csv('items.csv') print(item_list) print([item.total_price for item in item_list])
[Item(banana,10.0, 12), Item(apple,4.0, 6), Item(pear,7.0, 6)] [120.0, 24.0, 42.0]