Forum Discussion

Viji123's avatar
Viji123
Occasional Contributor
8 years ago

Unable to use a variable after importing unit1 in unit2

Hi All,

 

I am fairly new to testcomplete. Am using Python for scripting. I have 2 files under scripts - Unit1 and Unit2

 

I have imported unit1 in unit 2 as below

 

import Unit1

Unit1.Test1()

 

There is a variable in Unit1 file under the Test1() function. Am not able to use that variable in unit2. How can i get it

 

Please let me know

7 Replies

  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor
    I'm not too familiar with Python... however, if it is like most languages, a variable inside a function is scoped within the function. Even using the unit in an item her unit won't expose it. If you want that variable accessible to other units, it needs to be declared in a scope that is on the unit level, not within a function.
    • Viji123's avatar
      Viji123
      Occasional Contributor

      For example this is the scenario :

      file1 has the variables x1 and x2 how to pass them to file2 ?

      How can I import all of the variables from one to another?

       

      In python we have the below command

      from file1 import *

       

      This will import all objects and methods from file1. In spite of using this , am not able to access the variables of file1 in file 2 

  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor
    In Python, can you decare the variables just in the plain unit without having to wrap them in an object or method? If so, try that and see if that works for you.
  • Hello Viji123, 

     

    I am new to TC as well, and not sure if below will help you.

    I used Python for scripting as well. This is what I did based on your situation:

     

    if you just declar the variable outside of function in Unit1, and import Unit1 to Unit2, then you can call the varaible.

     

    Example:

     

    Unit1 script looks like below:

     

    var variable_from_unit1 = "Unit 1 variable"

     

     

    Unit2 script looks like below:

     

    import unit1

     

    def get_unit1_variable():

      Log.Message(Unit1.variable_from_unit1)

     

     

    When you run the Unit2 script, you should get a messag "Unit 1 variable"

     

     

     

     

    • Viji123's avatar
      Viji123
      Occasional Contributor

      Hi shenyusun,

       

      Thanks for the reply. I will try that out.

       

      I would also like to know how i can call the variable which declared inside a function in Unit1 file from a Unit2 file

      • shenyusun's avatar
        shenyusun
        Contributor

        I think when you declared a variable inside a function, the variable becomes private variable, and it can only be access within the function itself.