asweigart / pyperclip

Python module for cross-platform clipboard functions.
https://pypi.python.org/pypi/pyperclip
BSD 3-Clause "New" or "Revised" License
1.6k stars 193 forks source link

TypeError: 'dict' object is not callable #243

Open SDAndrews opened 1 year ago

SDAndrews commented 1 year ago

Hi team,

Hope everyone is well.

Warning before I begin: novice coder here.

I'm using the pyperclip module as part of @asweigart's amazing 'Automate the...' book and am currently in chapter 6: manipulating strings. One of the chapter projects focuses on Multi-Clipboard Automatic Messages. In this project Al's code (below) is left in a file called mclip.py but called via batch file and the Windows-R short cut. A sample command is "mclip busy." I've got all the components working together but I keep generating an error message that states "TypeError: 'dict' object is not callable"

As far as I can understand the command line is objecting to this line "pyperclip.copy(TEXT(keyphrase)) " but I'm unclear on how to fix it. Any ideas would be appreciated.

`#! python3

mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""", 'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?""", 'Absence': """ I'm not in the office that day """}

import sys, pyperclip if len(sys.argv) < 2: print('Usage: python mclip.py [keyphrase] - copy key text') sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT: pyperclip.copy(TEXT(keyphrase)) print('Text for ' + keyphrase + ' copied to the clipboard') else: print('There is no text for ' + keyphrase)`

timbr0wn commented 1 year ago

Hi Steven! The problem is caused by TEXT(keyphrase), because TEXT is a dictionary, but you are attempting to call it like a function (hence the "TypeError: 'dict' object is not callable").

If you are sure that the key exists in your dictionary, like you are inside the if block, then you can use square brackets [] to get the value associated with the dictionary key. In your scenario, that would be TEXT[keyphrase]

Alternatively, you could also do TEXT.get(keyphrase), which will return None if the key is not found instead of raising an error. You can also set your own default value instead of None. For example, you could do TEXT.get(keyphrase, "my fallback value")