ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

NameError: global name 'NAME' is not defined <SOLVED>

asked 2016-10-13 13:56:56 -0600

DannyMB gravatar image

updated 2016-10-18 22:46:11 -0600

Hi people! :) i am listening GPS's data and i want use them in another part of my code, for do Path Planing, but when I try to use them, it give me back this error

I defined variable global (global Lon, Lat) in many places like inside of def listener(), def backlatitud(): and def backlongitud() and it give back the same error.

Traceback (most recent call last):
  File "/home/pi/ros_catkin_ws/src/ceres_pkg/src/", line 25, in <module>
  File "/home/pi/ros_catkin_ws/src/ceres_pkg/src/", line 20, in listener
    print Lat
NameError: global name 'Lat' is not defined

This is my code:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
global Lon, Lat

def backlatitud(data1):
    Lat = float(
    #rospy.loginfo('Latitud %s',

def backlongitud(data):
    Lon = float(
    #rospy.loginfo('longitud %s', Lon)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("/latitud", String, backlatitud)
    rospy.Subscriber("/longitud", String, backlongitud)
    print Lat
    print Lon

if __name__ == '__main__':
edit retag flag offensive close merge delete


Please format code & console copy/pastes using the Preformatted Text button (the one with 101010 on it) in the future. That makes things much easier to read. Thanks.

gvdhoorn gravatar image gvdhoorn  ( 2016-10-13 14:29:47 -0600 )edit

Also: how is this related to NameError: global name 'NAME' is not defined?

gvdhoorn gravatar image gvdhoorn  ( 2016-10-13 14:30:25 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2016-10-13 16:57:03 -0600

Mani gravatar image

In your listener() function, Lat and Lon are being accessed prior to any initialisation. If you remove the two print statements before rospy.spin(), your code should work fine.

edit flag offensive delete link more


Yes, that work fine, but I need work with this variables (Lat and Lon) in another function, how do I call them?

for example def function(): LatNew = 2 * Lat LonNew = 2 * Lon Print LatNew Print LonNew

DannyMB gravatar image DannyMB  ( 2016-10-13 17:40:05 -0600 )edit

I'd recommend you use a class, instead of a flat file with a set of free functions. That would work-around all the issues you are having.

gvdhoorn gravatar image gvdhoorn  ( 2016-10-14 03:19:18 -0600 )edit

thanks @gvdhoom that's true, I did include a class, look at my final code C:\fakepath\Captura.JPG

DannyMB gravatar image DannyMB  ( 2016-10-18 22:39:18 -0600 )edit

Please don't use screenshots to post what is essentially text.

gvdhoorn gravatar image gvdhoorn  ( 2016-10-19 01:43:35 -0600 )edit

Question Tools

1 follower


Asked: 2016-10-13 13:56:56 -0600

Seen: 16,658 times

Last updated: Oct 18 '16