0

I have been using python for a while know but have never had this issue before. Whenever I go to create a function in my python file it doesn't give me any errors, but when I go to use the function it tells me its not defined.

Heres the code:

import pyautogui
import keyboard
import time

while True:
    try:
        if keyboard.is_pressed('`'):
            macro('hold','w',3)
            break
    except:
        break

def macro(type,key,seconds):
    endtime = time.time() + seconds
    while time.time() < endtime:
        if type == 'hold':
            pyautogui.hold(key)

The macro('hold','w',3) on line 8 is where the error "macro" is not defined is.

I've checked several different post but they are all different to this.

1
  • you execute the while loop before macro is defined, place the while loop after macro Commented Oct 7, 2023 at 1:19

2 Answers 2

0

The first block of code is being executed before the function is defined in the second block.

The common way to deal with this is to put your main block of code (while ...) inside a def main(): function, then call it at the end of the file.

But you can also just move everything down if you want.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thanks its just random simple things like this that I overlook and need a second pair of eyes to tell me what I did wrong.
0

Python function definitions can be considered executable, with the effect of binding the function name to its implementation. This happens at whatever point the definition appears. You cannot call a function by name before it has been bound, and Python does not have forward declarations.

Just move the function definition before the first point where you want to call it:

import pyautogui
import keyboard
import time

def macro(type,key,seconds):
    endtime = time.time() + seconds
    while time.time() < endtime:
        if type == 'hold':
            pyautogui.hold(key)

while True:
    try:
        if keyboard.is_pressed('`'):
            macro('hold','w',3)
            break
    except:
        break

Do understand that the "before" here is temporal, not positional. These two senses are related in Python, but not necessarily the same.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.